The Wayback Machine - https://web.archive.org/web/20231210205742/https://www.geeksforgeeks.org/double-forking-prevent-zombie-process/
Open In App
Related Articles

Double forking to prevent Zombie process

Improve Article
Improve
Save Article
Save
Like Article
Like

We have discussed Three methods of Zombie Prevention. This article is about one more method of zombie prevention.

Zombie Process: A process which has finished the execution but still has entry in the process table to report to its parent process is known as a zombie process. A child process always first becomes a zombie before being removed from the process table.

How Creating a Grandchild / Double Forking helps?

  1. The parent calls wait and creates a child. The child creates a grandchild and exits.
  2. The grandchild executes its instruction(task) and eventually it terminates. As the child has already exited, the grandchild will be taken care by init process.
  3. Init collect the exit status of grandchild. Hence the grandchild is not a zombie.

Note: Child is not a zombie as the parent called wait. Also in this case, the parent cannot verify the exit status of grandchild.




// C program of zombie prevention by
// creating grandchild or double forking
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/wait.h>
  
int main()
{
    pid_t pid;
  
    // fork first time
    pid = fork();
  
    if (pid == 0)
    {
        // double fork
        pid = fork();
        if (pid == 0)
            printf("Grandchild pid : %d\n Child"
               " pid : %d\n", getpid(), getppid());
    }
  
    else
    {
        wait(NULL);
        sleep(10);
    }
}


If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 30 May, 2017
Like Article
Save Article
Previous
Next
Similar Reads