经典2fork解决僵死进程

目的是父进程异步等待,子进程不变僵尸进程,(让子进程属于init)

。如果一个进程要f o r k一个子进程,但不要求它等待
子进程终止,也不希望子进程处于僵死状态直到父进程终止,实现这一要求的诀窍是调用fork
两次。
在第二个子进程中调用s l e e p以保证在打印父进程I D时第一个子进程已终止。在f o r k之后,
父、子进程都可继续执行——我们无法预知哪一个会先执行。如果不使第二个子进程睡眠,则
在fork之后,它可能比其父进程先执行,于是它打印的父进程I D将是创建它的父进程,而不是init进程
#include <sys/wait.h>   
#include <stdio.h>
#include <stdlib.h>

int
main(void)
{
    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);    /* parent from second fork == first child */

        /*
         * We're the second child; our parent becomes init as soon
         * as our real parent calls exit() in the statement above.
         * Here's where we'd continue executing, knowing that when
         * we're done, init will reap our status.
         */
        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");
    
    /*
     * We're the parent (the original process); we continue executing,
     * knowing that we're not the parent of the second child.
     */
    exit(0);
}

你可能感兴趣的:(fork)