您的位置:首页 > 其它

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

2013-09-07 23:12 260 查看
当我们只fork()一次后,存在父进程和子进程。这时有两种方法来避免产生僵尸进程:

父进程调用waitpid()等函数来接收子进程退出状态。
父进程先结束,子进程则自动托管到Init进程(pid = 1)。

目前先考虑子进程先于父进程结束的情况:

若父进程未处理子进程退出状态,在父进程退出前,子进程一直处于僵尸进程状态。
若父进程调用waitpid()(这里使用阻塞调用确保子进程先于父进程结束)来等待子进程结束,将会使父进程在调用waitpid()后进入睡眠状态,只有子进程结束父进程的waitpid()才会返回。 如果存在子进程结束,但父进程还未执行到waitpid()的情况,那么这段时期子进程也将处于僵尸进程状态。

由此,可以看出父进程与子进程有父子关系,除非保证父进程先于子进程结束或者保证父进程在子进程结束前执行waitpid(),子进程均有机会成为僵尸进程。那么如何使父进程更方便地创建不会成为僵尸进程的子进程呢?这就要用两次fork()了。

父进程一次fork()后产生一个子进程随后立即执行waitpid(子进程pid, NULL, 0)来等待子进程结束,然后子进程fork()后产生孙子进程随后立即exit(0)。这样子进程顺利终止(父进程仅仅给子进程收尸,并不需要子进程的返回值),然后父进程继续执行。这时的孙子进程由于失去了它的父进程(即是父进程的子进程),将被转交给Init进程托管。于是父进程与孙子进程无继承关系了,它们的父进程均为Init,Init进程在其子进程结束时会自动收尸,这样也就不会产生僵尸进程了。

[cpp] view
plaincopyprint?

#include <stdio.h>

#include <sys/wait.h>

#include <sys/types.h>

#include <unistd.h>

int main(void)

{

pid_t pid;

if ((pid = fork()) < 0)

{

fprintf(stderr,"Fork error!/n");

exit(-1);

}

else if (pid == 0) /* first child */

{

if ((pid = fork()) < 0)

{

fprintf(stderr,"Fork error!/n");

exit(-1);

}

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

{

fprintf(stderr,"Waitpid error!/n");

exit(-1);

}

/*

* We're the parent (the original process); we continue executing,

* knowing that we're not the parent of the second child.

*/

exit(0);

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: