Search code examples
cunixforkposixwaitpid

What's this fork-based pattern?


while searching for accept4(2) page, i came across the interesting code below. can anyone help me understand this fork-pattern please? (:

        /* Make the process the grandchild so we don't have to worry about waiting for it later.  */

        if  (pid != 0)  {
#ifdef  HAVE_WAITPID
                while  (waitpid(pid, (int *) 0, 0) < 0  &&  errno == EINTR)
                        ;
#else
                PIDTYPE wpid;
                while  ((wpid = wait((int *) 0)) != pid  &&  (wpid >= 0 || errno == EINTR))
                        ;
#endif

. not looking for difference in wait(2) vs waitpid(2) but specifically 'grandson' comment in the code.

.. did refer this What does wait() do on Unix? but not useful.

thanks, ~viren


Solution

  • Looks like the code before is made to launch a process in a way that its life is entirely detached from that running code. So a child of a child is ran to exec the interesting code, but the intermediate process (the direct child) need to be removed from the process list, so the waiting code to remove the zombie. The full pattern is probably that one:

    if (fork()==0) { // child
        if (fork()==0) { /// gran child
            // interesting things happens here in "detached" mode
            exec(..;);
            exit(...);
        }
        // direct child is of no use,
        // just to build the detached granchild,
        // disappear immediatly
        exit(...);
    }
    wait(...); // need to remove the child zombie (wait or waitpid)