这个基于叉子的模式是什么?

What's this fork-based pattern?

在搜索 accept4(2) 页面时,我发现了下面有趣的代码。谁能帮我理解这个分叉模式? (:

        /* 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

。不是在寻找 wait(2) 与 waitpid(2) 的区别,而是在代码中特别 'grandson' 注释。

.. 确实提到了这个 What does wait() do on Unix? 但没有用。

谢谢, ~viren

看起来之前的代码是以一种完全脱离 运行 代码的方式启动进程的。所以一个child的child是运行 exec有趣的代码,但是中间进程(直接child)需要从进程列表中移除,所以等待代码移除僵尸。 完整的模式可能是那个:

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)