进程一旦调用了wait函数,就立即阻塞周记,用wait自动分析是否当前的进程的某个子进程已经退出,如果让它找到了这样一个已经变成僵尸的子进程,wait就会收集这个子进程的消息,并把它彻底销毁后返回;如果没有找到这样一个子进程,wait就会一直阻塞在这里,直到有一个出现为止。
//头文件
#include <sys/types.h>
#include <sys/wait.h>
//函数原型
pid_t wait(int *status);
wait会暂时停止目前进程的执行,直到有信号来到或者子进程结束。如果在调用wait时子进程已经结束,则wait会立即返回子进程结束状态值。子进程的结束状态值会由参数status返回。而子进程的进程ID也会一块返回。如果不需要状态值,则将参数status设置成NULL。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
/*使用wait函数回收子进程*/
int main()
{
/*fork一个子进程*/
pid_t pid = fork();
if (pid > 0)/*父进程*/
{
printf("int parent process\n");
pid_t pr = wait(NULL);
printf("int parent process,I catched a child process with pid of %d!\n", pr);
}
else if (pid == 0)/*子进程*/
{
/*子进程退出,成为一个僵尸进程*/
printf("Sub-process,PID: %u, PPID: %u\n", getpid(), getppid());
sleep(5);
exit(0);
}
return 0;
}
/*使用wait函数回收子进程*/