linux环境编程-wait(僵尸进程回收)
linux环境编程-wait(僵尸进程回收)
前面我们介绍了什么是僵尸进程,今天我们来看看 怎么回收 进程残留的PCB
还是老规矩 看看视频 了解一下
求关注
#include
#include
pid_t wait (int * status);
wait
()会暂时停止目前进程的执行,直到有信号来到或子进程结 束。如果在调用 wait
()时子进程已经结束,则
wait
()会立即返 回子进程结束状态值。子进程的结束状态值会由参数 status
返回, 而子进程的进程识别码也会一快返回。如果不在意结束状态值,则 参数 status
可以设成
NULL
。子进程的结束状态值请参考
waitpid
()。 如果执行成功则
返回子进程识别码(PID)
,如果有错误发生则返回 -1。失败原因存于
errno
中。
总结说说这个函数 的三个功能把
父进程 调用它 就 阻塞等待 子进程 结束
回收子进程残留的 资源
获取子进程结束的状态
看看一些判断返回状态的宏【我用有道翻译成中文了,方便大家了解】
1.WIFEXITED (stat_val)
如果为正常终止的子进程返回状态,则计算为非零值。
2.WEXITSTATUS (stat_val)
如果WIFEXITED(stat_val)的值非零,那么这个宏将计算为status参数的8位低阶值
子进程传递给_exit()或exit()的值,或者子进程从main()返回的值。
3.WIFSIGNALED (stat_val)
如果由于接收到信号而终止的子进程返回状态,则计算为非零值
未捕获(参见)。
4.WTERMSIG (stat_val)
如果wifsignal (stat_val)的值为非零,该宏将计算导致ter‐的信号的数量
子进程的最小值。
5.WIFSTOPPED (stat_val)
如果为当前停止的子进程返回状态,则计算为非零值。
6.WSTOPSIG (stat_val)
如果WIFSTOPPED(stat_val)的值非零,那么这个宏将计算产生子元素的信号的数量
过程停止。
7.WIFCONTINUED (stat_val)
如果从作业控制停止后继续的子进程返回状态,则计算为非零值。
代码Demo
#include
#include
#include
using namespace std;
int
main(int argc, char*argv[])
{
pid_t pid, wpid;
pid = fork();
if(pid == 0){
cout << "hello world!" << endl;
sleep(60);
}else if(pid > 0){
printf("I am parent, ID: %u\n", getpid());
int status;
printf("wait son die....\n");
if((wpid = wait(&status)) == -1){// block wait son progress die
perror("wait error");
exit(1);// clear the PCB of son
}// get reason about son's die
if(WIFEXITED(status)!=0 && WIFSIGNALED(status)==0){
printf("son progress normal exit\n");
printf("son progress exit status : %d \n", WEXITSTATUS(status));
}else{// 0
printf("son expretion exit,signal ID:%d \n", WTERMSIG(status));
}
printf("I am parent, ID: %u, wait son ID: %u \n", getpid(), wpid);
}else{
perror("fork error");
exit(1);
}
return 0;
}
效果:
linux环境编程-wait(僵尸进程回收)相关教程