如果一个进程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