I am new to UNIX programming and i was reading about zombie processes and how to avoid them using fork() twice. I read the code from a book and tried to run it on my system.. I am using ubuntu 12.04. I ran the following code:
#include<stdio.h>
#include<sys/wait.h>
#include<stdlib.h>
int main()
{
pid_t pid;
if(pid = fork() < 0)
printf("Fork Error.!!!\n");
else
if(pid == 0)
{
if((pid = fork()) < 0)
printf("Fork2 Error.!!!\n");
else
if(pid > 0)
exit(0);
sleep(2);
printf("Second Child, parent id: %d\n", getppid());
exit(0);
}
if(waitpid(pid, NULL, 0) != pid)
printf("Waitpid Error.!!!\n");
exit(0);
}
The output that i get is as follows:
Second Child, parent id: 1
Second Child, parent id: 1
The book says this should be printed only once and that is also what i feel should happen when i see what’s happening in the code. I dont understand why its getting printed twice. I found this code at many places on the net but could not get something that explains this. Any help is welcome. Thanks.!!
second line of the code in main – missing brackets around
pid = fork()