码迷,mamicode.com
首页 > 系统相关 > 详细

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

时间:2014-11-05 12:11:03      阅读:379      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   color   ar   for   sp   div   on   

#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);
  }
  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,并释放进程表项。
 

 

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

标签:style   blog   io   color   ar   for   sp   div   on   

原文地址:http://www.cnblogs.com/leijiangtao/p/4075706.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!