To give the program will generate a zombie, run observation.
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/wait.h>
int main ()
{
int pid;
pid = fork();
if(pid > 0)//father process
{
int i = 1;
while(i <= 12)
{
sleep(1);
i += 1;
}
}
else if(pid == 0)//son process
{
int j = 1;
while(j <= 4)
{
sleep(1);
j += 1;
}
exit(0);
}
return 0;
}
It can be clearly seen by the results, when about 4s after the end of the child, then the parent process and about 8s time to end, which resulted in 4 ~ 12s between the child process becomes a zombie process.
The following procedure is based on the transformation of the above, namely the use of two fork () to avoid a zombie.
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<sys/wait.h>
int main ()
{
int pid;
pid = fork();
if(pid > 0)//father process
{
wait(0);//waiting for the end of son process
int j = 1;
while(j <= 12)
{
sleep(1);
j ++;
}
}
else if(pid == 0)//son process
{
int pid2;
pid2 = fork();
if(pid2 > 0)//son process
{
exit(0);
}
else if(pid2 == 0)//grandson process
{
int i = 1;
while(i <= 4)
{
sleep(1);
i ++;
}
exit(0);
}
}
return 0;
}