1 //调用fork函数创建子进程, 并完成对子进程的回收,并输出回收进程的信息
 2 #include <stdio.h>
 3 #include <stdlib.h>
 4 #include <string.h>
 5 #include <sys/types.h>
 6 #include <unistd.h>
 7 #include <sys/wait.h>
 8 
 9 int main()
10 {
11     int i = 0;
12     int n = 3;
13 
14     for(i=0; i<n; i++)    
15     {
16         //fork子进程
17         pid_t pid = fork();
18         if(pid<0) //fork失败的情况
19         {
20             perror("fork error");
21             return -1;
22         }
23         else if(pid>0) //父进程
24         {
25             printf("father: fpid==[%d], cpid==[%d]\n", getpid(), pid);
26             sleep(1);
27         }
28         else if(pid==0) //子进程
29         {
30             printf("child: fpid==[%d], cpid==[%d]\n", getppid(), getpid());
31             break;
32         }
33     }
34 
35     //父进程
36     if(i==3)
37     {
38         printf("[%d]:father: fpid==[%d]\n", i, getpid());
39         pid_t wpid;
40         int status;
41 
42         while(1)
43         {
44             wpid = waitpid(-1, &status, WNOHANG);
45             if(wpid==0) // 没有子进程退出
46             {
47                 continue;
48             }            
49             else if(wpid==-1) //已经没有子进程了
50             {
51                 printf("no child is living, wpid==[%d]\n", wpid);
52                 exit(0);
53             }
54             else if(wpid>0) //有子进程退出
55             {
56                 if(WIFEXITED(status))
57                 {
58                     printf("normal exit, status==[%d]\n", WEXITSTATUS(status));
59                 }
60                 else if(WIFSIGNALED(status))
61                 {
62                     printf("killed by signo==[%d]\n", WTERMSIG(status));
63                 }
64             }
65         }
66     }
67 
68     //第1个子进程
69     if(i==0)
70     {
71         printf("child1's pid=%d\n",getpid());
72         execl("/bin/ls", "ls", "-l", NULL);
73         return 0;
74     }
75 
76     //第2个子进程
77     if(i==1)
78     {
79         printf("child2's pid=%d\n",getpid());
80         execl("/home/sm7/summer/c/jinc/test2","test2",NULL);
81         return 0;
82     }
83 
84     //第3个子进程
85     if(i==2)
86     {
87         printf("child3's pid =%d\n",getpid());
88         execl("/home/sm7/summer/c/jinc/test2","test2",NULL);
89         return 0;
90     }
91 
92     return 0;
93 }