进程结束,会在内存中存留PCB进程控制块,需要使用wait来回收
函数的3个功能
阻塞等待子进程退出
回收子进程的残留资源
获取子进程的结束状态
pid_t wait(int *stat_loc);
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <pthread.h>
int main(int agrc, char *argv[])
{
pid_t pid, wpid;
int status;
pid_t pid = fork();
if (pid==-1){
perror("fork error");
exit(1);
}else if(pid==0){ // 子进程
sleep(10);
printf("child die ----------");
return 73;
}else if (pid>0){ // 父进程
printf("I'm parent: %d\n");
// 可以status传入null, 不关心子进程结束原因
wpid = wait(&status);
if(wpid == -1){
perror("wait error");
exit(1);
}
if (WIFEXITED(status)){
printf(WEXITSTATUS(status));
}// 为真, 说明子进程正常终止
if (WIFSIGNALED(status)){
printf("child kull with signal", WTERMSIG(status));
} // 非正常终止
}
return 0;
}
pid_t waitpid(pid_t pid, int *stat_loc, int options);
pid的值
options的值
当options的值为WNOHANG指定回收方式为,非堵塞
返回值
waitpid(-1, &status, 0) == wait(&status);
不管用wait还是waitpid调用只能清理一个子进程
原文:https://www.cnblogs.com/fandx/p/12518114.html