C program to avoid zombie process by forking twice

wait and waitpid Functions:
When a process terminates, either normally or abnormally, the kernel notifies the parent by sending the SIGCHLD signal to the parent. Because the termination of a child is an asynchronous event – it can happen at any time while the parent is running – this signal is the asynchronous notification from the kernel to the parent. The parent can choose to ignore this signal, or it can provide a function that is called when the signal occurs: a signal handler. A process that calls wait or waitpid can:

  •  Block, if all of its children are still running
  • Return immediately with the termination status of a child, if a child has terminated and is waiting for its termination status to be fetched
  • Return immediately with an error, if it doesn’t have any child processes.
				
					#include<stdio.h> 
#include <sys/wait.h> 
#include<errno.h> 
#include<stdlib.h>

int main()
{
pid_t pid;
if ((pid = fork()) < 0)
{
printf("fork error");
}
else if (pid == 0)
{ /* first child */
if ((pid = fork()) < 0)
printf("fork error");
else if (pid > 0)
exit(0);
sleep(2);
printf("second child, parent pid = %d\n", getppid()); exit(0);
}
if (waitpid(pid, NULL, 0) != pid) /* wait for first child */
printf("waitpid error");
exit(0);
}
				
			

Leave a Reply