1. As shown in the following code
#include <unistd.h>#include<sys/types.h>#include<unistd.h>intMainintargcChar*argv[]) {pid_t child=Fork (); if(Child = =-1) {//Errorprintf"\nfork child error."); Exit (0); } Else if(Child = =0){ //exit (0); if(Child = fork ()) <0) printf ("Fork error\n"); Else if(Child >0) {//sleep (3);Exit0); } Sleep (5); printf ("second child,parent pid%d\n", Getppid ()); Exit (0); }//sleep (3); if(Waitpid (Child,null,0) !=Child ) printf ("waitpid error\n"); Sleep (Ten); Exit (0); //sleep (+);}
1 terminals are ready to execute after the test program is generated using GCC-G test.c-o test.
Another 1 terminals constantly tapping command PS Lfx | grep test, where the 3rd column shows the PID, and the 4th column shows ppid.
You can see another 1 terminals showing:
0 0 28787 20574 0 3920 340 hrtime s+ PTS/1 0:00 | \_./test
0 0 28792 20817 0 103248 828 pipe_w s+ pts/2 0:00 \_ grep test
1 0 28789 1 0 3920 hrtime s+ pts/1 0:00/test
Where the 3rd Act we fork the second sub-process, its ppid has been 1 (that is, the init process)
The 1th line of the test process is the main process at sleep (10), which achieves our goal.
2. Here is the main discussion of the use of the waitpid here
Function: Reclaim the sub-process generated by the 1th Fork, where the code shows that the child process is generated immediately after calling exit.
3. Doubts: the fork function after the parent-child process sequence of execution, Waitpid always successful recovery?
To do 2 experiments here,
The first time the code in line 20th sleep (3), uncomment, run, observe the results. (A zombie process is generated after the main process Waitpid execution)
The second time the code in the 27th line sleep (3), uncomment, run, observe the results. (The main process waitpid the zombie process before execution)
There were no zombie processes in the last 2 experiments, and the instructions were successfully recovered.
In the 2nd experiment, the zombie process probably existed for about 3 seconds, due to sleep on line 27th (3).
The waitpid of the main process in the visible code always succeeds in recovering the child process of the first fork.
2 times use fork to avoid zombie processes and not to process SIGCHLD signals