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

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