- 论坛徽章:
- 0
|
apue中提到调用fork两次以避免僵死进程,代码是这样的
#include "apue.h"
#include <sys/wait.h>
int
main(void)
{
pid_t pid;
if ((pid = fork()) < 0) {
err_sys("fork error");
} else if (pid == 0) { /* first child */
if ((pid = fork()) < 0)
err_sys("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 */
err_sys("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,因为如果把代码改成如下这样,也可以避免产生僵死进程
int
main(void)
{
pid_t pid;
if ((pid = fork()) < 0) {
err_sys("fork error");
} else if (pid == 0) { /* first child */
sleep(2);
printf("second child, parent pid = %d\n", getppid());
exit(0);
}
exit(0);
}
父进程调用一次fork后,直接调用exit结束,那么子进程同样会被init进程接收
同样不会产生僵死进程,
为什么必须调用两次呢,是有什么深意吗
请指教 |
|