調用fork兩次以避免僵死進程

如果一個進程fork一個子進程,但不要它等待子進程終止,也不希望子進程處於僵死狀態直到父進程終止,實現這一要求的技巧是調用fork2次。

下面是實例代碼:

  1. #include <stdio.h>  
  2. #include <stdlib.h>  
  3. #include <sys/wait.h>  
  4.   
  5. int main(void)  
  6. {  
  7.         pid_t pid;  
  8.   
  9.         if((pid = fork()) < 0) {  
  10.                 printf("error: fork error.\n");  
  11.         } else if(pid == 0) {  
  12.                 if((pid = fork()) < 0)  
  13.                         printf("error: fork error.\n");  
  14.                 else if(pid > 0)  
  15.                         exit(0);  
  16.                 /* we are the second child; our parent becomes init as soon as 
  17.                  * our real parent calls exit() in the statement above. Here is  
  18.                  * where we had continue executing , knowing that when we are  
  19.                  * done, init will reap our status.  
  20.                  */  
  21.                 sleep(2);  
  22.                 printf("second child, parent pid = %d\n", getppid());  
  23.                 exit(0);  
  24.         }  
  25.   
  26.         if(waitpid(pid, NULL, 0) != pid)  
  27.                 printf("error, waitpid error.\n");  
  28.   
  29.         exit(0);  
  30. }  

第二個字進程調用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


轉自http://blog.csdn.net/zhangjie201412

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章