首页 > 代码库 > exit和wait一起可以彻底清除子进程的资源

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);  }  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  process4596I catched a child process with pid of 4596parent process4595 child  process4597I catched a child process with pid of 4597parent process4595 child  process4598I catched a child process with pid of 4598当把exit注释后输出结果如下:parent process4642 child  process4643parent process4643 child  process4644parent process4644 child  process4645I catched a child process with pid of 4645I catched a child process with pid of 4644parent process4643 child  process4646I catched a child process with pid of 4646I catched a child process with pid of 4643parent process4642 child  process4647parent process4647 child  process4648I catched a child process with pid of 4648I catched a child process with pid of 4647parent process4642 child  process4649I catched a child process with pid of 4649//重新执行一边的结果parent process4657 child  process4658parent process4658 child  process4659parent process4659 child  process4660I catched a child process with pid of 4660I catched a child process with pid of 4659parent process4658 child  process4661I catched a child process with pid of 4661I catched a child process with pid of 4658parent process4657 child  process4662parent process4662 child  process4663I catched a child process with pid of 4663I catched a child process with pid of 4662parent process4657 child  process4664I catched a child process with pid of 4664从上面的输出结果可以得出:exit可以用来释放进程的资源,必须加上,当注释掉时,可能因为子进程的资源没有及时清理掉,所以导致wait阻塞住,不能及时清理掉子进程!总结:当进程发出exit该调用时,内核会释放进程占有的资源,释放进程上下文所占的内存空间,保留进程表项,将进程表项中记录进程状态的关键字设为僵死状态。内核在进程收到不可扑捉的信号时,会从内核内部调用exit,使得进程退出。父进程通过wait,并释放进程表项。 

 

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