多进程

/*exc.c*/

/*通过编写多进程程序,使读者熟练掌握fork、exec、wait、waitpid等函数的使用。该实验有3个进程,其中一个为父进程,其余两个是该父进程创建的子进程,其中一个子进程运行“ls -l”指令,另一个子进程在暂停5秒之后异常退出,父进程并不阻塞自己,并等待子进程的退出信息,待收集到该信息,父进程就返回。*/ 《嵌入式linux应用程序开发详解》第232页。

#include <sys/types.h>
#include <unistd.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <stdio.h>

int main(void)
{
   pid_t child1,child2,child;
   child1 = fork();
   child2 = fork();

   if(child1 == -1)
   {
       perror("child1 fork");
       exit(1);
   }
   else if(child1 == 0)
   {
       printf("In child1:execute 'ls -l'/n");
       if(execlp("ls","ls","-l",NULL)<0)
            perror("child1 execlp");
   }

   if(child2 == -1)
   {
       perror("child2 fork");
       exit(1);
   }
   else if(child2 == 0)
   {
       printf("In child2:sleep for 5 seconds and then exit /n");
       sleep(5);
       exit(0);
   }
   else
   {
       printf("In father process:/n");
       do
       {
           child = waitpid(child2,NULL,WNOHANG);
           if(child == 0)
           {
               printf("The child2 process has not exited! /n") ;
               sleep(1);
           }
       }while(child == 0);
      
       if(child == child2)
           printf("Get child2 /n");
       else
           printf("Error occured! /n");
   }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值