多进程

来源:互联网 发布:网页设计的软件 编辑:程序博客网 时间:2024/04/29 20:32

/*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");
   }

原创粉丝点击