fork俩次以避免僵死进程

19 篇文章 0 订阅

如果你想让一个进程fork一个子进程,单不要它等待子进程终止,也不希望子进程处于将死状态直到父进程终止,通过fork俩次就可以让 init 进程接管你的进程

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

 int 
 main(void)
 {
    pid_t pid;

    printf("current pid = %ld\n", (long)getpid());

    if ((pid = fork()) < 0) {
        printf("fork errot ");
    } else if (pid == 0)    {  /* first child */
        if ((pid = fork()) < 0 )  /* second child */
            printf("fork errot ");
        else if (pid > 0 ) {
            printf("exit pid = %ld\n", (long)getpid());
            exit(0); /* end the parent of the first child */
        }   
        /*
         * We're the scond 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("scond child , parent pid = %ld\n", (long)getppid());
        exit(0);
     }   

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

     exit(0);   
}     

查看进程是否是init 进程

ps aux | grep 7167
 7167 是我最后在shell 输出的 parent pid  ,我原来以为会是进程1 呢,结果不是
 我查看了 7167 发现它也是一个init 进程,所以如果你输出的不是1 那就自己查看一下
 是否是init 进程。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值