wait
函数原型:
#include<sys/types.h>
#include<sys/wait.h>
pid_t wait(int *wstatus);
- 返回值是等待退出进程的进程号。
- int *wstatus这个参数将保存子进程的状态信息,有了这个信息父进程就可以了解子进程为什么会推出,是正常推出还是出了什么错误。如果status不是空指针,则状态信息将被写入
器指向的位置。当然,如果不关心子进程为什么退出的话,也可以传入空指针。
Linux提供了一些非常有用的宏来帮助解析这个状态信息,这些宏都定义在sys/wait.h头文件中。主要有以下几个:
宏 | 说明 |
---|---|
WIFEXITED(wstatus) | 如果子进程正常结束,它就返回真;否则返回假。 |
WEXITSTATUS(wstatus) | 如果子进程正常结束,它就返回真;否则返回假。 |
WIFSIGNALED(wstatus) | 如果子进程因为一个未捕获的信号而终止,它就返回真;否则返回假。 |
WTERMSIG(wstatus) | 如果WIFSIGNALED(status)为真,则可以用该宏获得导致子进程终止的信号代码。 |
WIFSTOPPED(wstatus) | 如果当前子进程被暂停了,则返回真;否则返回假。 |
WSOPSIG(wstatus) | 如果WIFSTOPPED(status)为真,则可以使用该宏获得导致子进程暂停的信号代码。 |
wait是阻塞函数,当无法任意其他进程退出的返回值时就会暂停该进程,一直等待进程退出返回值的出现。
捕捉进程退出返回值这一过程交给内核自动处理。
wait函数示例:
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int main(){
pid_t pid;
pid=fork();
if(pid<0){
perror("fork error:");
return -1;
}
else if(pid==0){
sleep(5);
printf("%d",getpid());
printf("child process2\n");
exit(2);
}
else{
pid_t pidd;
pidd=fork();
if(pidd<0>){
perror("fork error");
return -1;
}
if(pidd==0){
sleep(5);
printf("%d",getpid());
printf("child process1\n");
exit(1);
}
else{
int status1=-1;
int status2=-1;
pid_t pidtmp1=wait(&status1);
pid_t pidtmp2=wait(&status2);
printf("%d %d %d %d %d %d\n",WEXITSTATUS(status1),pidtmp1,WEXITSTATUS(status2),pidtmp2,pid,getpid());
printf("parent process\n");
}
}
return 0;
}
输出结果:
6908child process2
6909child process1
2 6908 1 6909 6908 6907
parent process
waitpid
函数原型:
#include<sys/types.h>
#include<sys/wait.h>
pid_t waitpid(pid_t pid,int *wstatus,int option);
- pid_t pid,参数pid为欲等待的子进程识别码,其具体含义如下:
参数值 | 说明 |
---|---|
pid<-1 | 等待进程组好位pid绝对值的任何子进程 |
pid=-1 | 等待任何子进程,此时的waitpid函数就退化成了普通的wait函数。 |
pid=0 | 等待进程组号与目前进程相同的任何子进程,也就是说任何和调用waitpid函数的进程都在同一个进程组的进程。 |
pid>0 | 等待进程号为pid的子进程。 |
- int *wstatus同上
- int option提供了一些另外的选项来控制waitpid()函数的行为。如果不想使用这些选项,则可以把这个参数设为0。
主要使用的有以下两个选项:
参数 | 说明 |
---|---|
WNOHANG | 如果pid指定的子进程没有结束,则waitpid函数立即返回0,而不是阻塞等待,如果结束了则返回该子进程的进程号。 |
WUNTRACED | 如果自己成进入暂停状态,则马上返回。 |
示例:
#include <sys/types.h>
#include <unistd.h>
#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#include <wait.h>
int main(){
pid_t pid;
pid=fork();
if(pid<0){
perror("fork error:");
}
else if(pid==0){
sleep(5);
printf("%d",getpid());
printf("child process2\n");
exit(2);
}
else{
pid_t pidd;
pidd=fork();
if(pidd==0){
printf("%d",getpid());
printf("child process1\n");
exit(1);
}
else{
int status1=-1;
int status2=-1;
sleep(5);
pid_t pidtmp1=waitpid(-1,&status1,WNOHANG);
pid_t pidtmp2=waitpid(-1,&status2,WNOHANG);
printf("%d %d %d %d %d %d\n",WEXITSTATUS(status1),pidtmp1,WEXITSTATUS(status2),pidtmp2,pid,getpid());
printf("parent process\n");
}
}
return 0;
}
输出结果
5898child process1
1 5898 255 0 5897 5896
5897child process2
parent process
本文借鉴了《Linux中waitpid()函数的用法》链接:https://blog.csdn.net/Roland_Sun/article/details/32084825