I am wondering if the following code can create zombies:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
int main(){
int i=1;
pid_t p;
p = fork();
i++;
if(p!=0){
waitpid(p, NULL, 0);
}
printf("%d\n",i);
return 0;
}
So, the parent process calls the waitpid for the child process, which returns immediately if the child has not already exited. So, no zombies can arise so far. But, if the child exits before
return 0;command this would be a zombie then? I am actually confused about it. Should the waitpid be the last line of code before the program terminates? Any help would be appreciated. Thanks!
The child only becomes a zombie if it ends and the parent doesn't call
wait*()
as long as itself lives on.In the moment the parent also ends the child is reaped by the
init
process which will take care to callwait*()
on the child, so it will finally end and with this leave the zombie state and disappears from the process list.To provoke the child created in your example code to become a zombie modify the code for example as follows:
Due to the two following facts:
waitpid()
most probably will always failSIGCHLD
is to ignrore it.the code above in fact is the same as: