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

如果一个进程fork一个子进程,但不要它等待子进程终止,也不希望子进程处于僵死状态直到父进程终止,实现这一要求的技巧是调用fork2次。

下面是实例代码:

[cpp]  view plain copy
  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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值