Home > database >  Why is wait necessary in double fork to remove zombie process?
Why is wait necessary in double fork to remove zombie process?

Time:06-07

I'm not sure to understand why do we need to call wait() in the parent to take care of zombie process when double forking is supposed to take care of it ? Why do we need to double fork if wait() alone can already do the job ?

#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
        {
            exit(0);
        }
    }

    else
    {
        wait(NULL);
        sleep(10);
    }
}

CodePudding user response:

I'm not sure to understand why do we need to call wait() in the parent to take care of zombie process when double forking is supposed to take care of it ? Why do we need to double fork if wait() alone can already do the job ?

You misunderstand the purpose and usage of the double-fork idiom.

Background

Every process except pid 1 becomes a zombie when it terminates. The zombie persists in the process table until it is collected via one of the wait-family functions. If the process's parent is still alive then that is the one that must wait to collect it. Otherwise, the responsibility is transferred to process 1. A viable choice of program to run as process 1 will handle those very efficiently, so you will almost never see zombies that are waiting for process 1 to collect them.

Double forking

The point of a double fork is for the original process A to create a process that will be the responsibility of process 1 to clean up, despite A continuing to run. A fire & forget it situation, if you will. This is accomplished by forking a child B that immediately forks the wanted process, C. Process B then terminates to transfer responsibility for C to process 1 (not process A).

That does not relieve process A of its responsibility to wait for process B. But A can perform that wait right away and know that it won't be delayed very long, as opposed to either blocking until C terminates, or having to periodically check for C's completion, or leaving C as a zombie indefinitely, which would be the alternatives if A forked C directly.

  •  Tags:  
  • c
  • Related