头文件
#include<sys/types.h>
#include<sys/wait.h>
函数原型
pid_t wait (int * status);
参数 status 是一个整形指针。如果status不是一个空指针,则终止进程的终止状态将存储在该指针所指向的内存单元中。如果不关心终止状态,可以将 status参数设置为NULL。
调用 wait 函数时,调用进程将会出现下面的情况:
- 如果其所有子进程都还在运行,则阻塞。
- 如果一个子进程已经终止,正等待父进程获取其终止状态,则获取该子进程的终止状态然后立即返回。
- 如果没有任何子进程,则立即出错返回
2. 代码测试
#include<stdio.h>
#include<stdlib.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
int main()
{
pid_t pid;
int status,i;
int cnt = 0;
pid = fork();
if(pid > 0){
wait(&status);
i=WEXITSTATUS(status);
printf("child pid =%d ,exit status=%d\n",getpid(),i);
while(1){
printf("cnt: %d",cnt);
printf("This is the parent print,pid:%d\n",getpid());
sleep(1);
}
}else if(pid == 0){
while(1){
printf("This is the child print,pid =%d\n",getpid());
sleep(1);
cnt++;
printf("cnt: %d",cnt);
if(cnt == 5){
exit(5);
}
}
}
return 0;
}