如果一個進程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