调用fork两次以避免僵死进程

如果一个进程fork一个子进程,但不要它等待子进程终止,也不希望子进程处于僵死状态直到父进程终止,实现这一要求的技巧是调用fork2次。

下面是实例代码:

#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>

int main(void)
{
        pid_t pid;

        if((pid = fork()) < 0) {
                printf("error: fork error.\n");
        } else if(pid == 0) {
                if((pid = fork()) < 0)
                        printf("error: fork error.\n");
                else if(pid > 0)
                        exit(0);
                /* we are the second child; our parent becomes init as soon as
                 * our real parent calls exit() in the statement above. Here is 
                 * where we had continue executing , knowing that when we are 
                 * done, init will reap our status. 
                 */
                sleep(2);
                printf("second child, parent pid = %d\n", getppid());
                exit(0);
        }

        if(waitpid(pid, NULL, 0) != pid)
                printf("error, waitpid error.\n");

        exit(0);
}

第二个字进程调用sleep以保证在打印父进程ID时第一个字进程已终止。在fork之后,父子进程都可以继续执行,并且我们无法预知哪个会限制性。在fork之后,如果不是第二个子进程休眠,那么它可能比其父进程先执行,于是它打印的父进程ID将是创建它的父进程,而不是init进程。

一下是执行结果

jay@jay-vibox:~/workspace/UNIX/8-5$ cc main.c 
jay@jay-vibox:~/workspace/UNIX/8-5$ ./a.out 
jay@jay-vibox:~/workspace/UNIX/8-5$ second child, parent pid = 1

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值