exit和wait一起可以彻底清除子进程的资源

#include<stdio.h> 
#include<unistd.h> 
#include<sys/types.h> 
#include<stdlib.h>
#include <errno.h> 
int main() 
{
  pid_t p1,p2,pr; 
  int i; 
  for(i=0;i<=2;i++)
  { 
  if((p1=fork())==0)
  { 
  printf("parent process%d child  process%d\n",getppid(),getpid()); 
  exit(0); //我发现把return 0替换为exit(0)也可以的!,不过编译器这两种的处理区别很大,以后再做解释
  }
  else{
  pr=wait(NULL);
//如果成功,wait会返回被收集的子进程的进程ID,
//如果调用进程没有子进程,调用就会失败,此时wait返回-1,同时errno被置为ECHILD。
  if( pr>0)  
   printf("I catched a child process with pid of %d\n", pr); 
  else  
   printf("error: %s\n.\n", strerror(errno)); 
  }
 }
 return 0;
} 
输出结果如下:
parent process4595 child  process4596
I catched a child process with pid of 4596
parent process4595 child  process4597
I catched a child process with pid of 4597
parent process4595 child  process4598
I catched a child process with pid of 4598
当把exit注释后输出结果如下:
parent process4642 child  process4643
parent process4643 child  process4644
parent process4644 child  process4645
I catched a child process with pid of 4645
I catched a child process with pid of 4644
parent process4643 child  process4646
I catched a child process with pid of 4646
I catched a child process with pid of 4643
parent process4642 child  process4647
parent process4647 child  process4648
I catched a child process with pid of 4648
I catched a child process with pid of 4647
parent process4642 child  process4649
I catched a child process with pid of 4649
//重新执行一边的结果
parent process4657 child  process4658
parent process4658 child  process4659
parent process4659 child  process4660
I catched a child process with pid of 4660
I catched a child process with pid of 4659
parent process4658 child  process4661
I catched a child process with pid of 4661
I catched a child process with pid of 4658
parent process4657 child  process4662
parent process4662 child  process4663
I catched a child process with pid of 4663
I catched a child process with pid of 4662
parent process4657 child  process4664
I catched a child process with pid of 4664
从上面的输出结果可以得出:exit可以用来释放进程的资源,必须加上,当注释掉时,可能因为子进程的资源没有
及时清理掉,所以导致wait阻塞住,不能及时清理掉子进程!
总结:当进程发出exit该调用时,内核会释放进程占有的资源,释放进程上下文所占的内存空间,保留
进程表项,将进程表项中记录进程状态的关键字设为僵死状态。内核在进程收到不可扑捉的信号时,会从内核内部调用exit
,使得进程退出。父进程通过wait,并释放进程表项。
 

 

转载于:https://www.cnblogs.com/leijiangtao/p/4075706.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值