wait函数
pid_t wait(int *status);
功能:
阻塞并等待子进程退出
回收子进程残留资源
获取子进程结束状态(退出原因)
返回值:
成功:清理掉的子进程ID
失败:-1 (没有子进程)
参数:子进程的退出状态 -- 传出参数
1. WIFEXITED(status):为非0 → 进程正常结束
WEXITSTATUS(status):
如上宏为真,使用此宏 → 获取进程退出状态 (exit/return)的参数)
2. WIFSIGNALED(status):为非0 → 进程异常终止
WTERMSIG(status):
如上宏为真,使用此宏 → 取得使进程终止的那个信号的编号。
测试源码
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <sys/wait.h>
int counter = 200;
int main(int argc, const char* argv[])
{
int i;
pid_t pid;
for(i=0; i<5; ++i)
{
pid = fork();
if(pid == 0)
{
break;
}
}
if(i<5)
{
counter += 300;
printf(" child process , pid = %d, ppid = %d\n", getpid(), getppid());
printf("counter = %d\n\n", counter);
}
else if(i == 5)
{
counter += 100;
printf(" parent process, pid = %d, ppid = %d\n", getpid(), getppid());
printf("counter = %d\n\n", counter);
sleep(1);
int status;
pid_t wpid;
while((wpid = wait(&status)) != -1 )
{
printf("child process died, pid = %d\n", wpid);
if(WIFEXITED(status))
{
printf("process exit value: %d\n", WEXITSTATUS(status));
}
else if(WIFSIGNALED(status))
{
printf("process exit by signal: %d\n", WTERMSIG(status));
}
}
}
}
测试结果:
关键代码分析
1、父子进程之间,对于counter,创建了不同的用户空间,所以每一个进程之间counter的初始值均为200。
2、wait函数会等待子进程执行完毕后父进程再退出。
3、子进程的退出状态,由传入的参数决定,所以这样可以作为一个判断,进而做进一步的处理。