您的位置:首页 > 其它

fork俩次以避免僵死进程

2016-09-27 10:47 204 查看
如果你想让一个进程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 进程。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: