wait和waitpid详解
1、wait
- 头文件
#include <sys/types.h>
#include <sys/wait.h>
- 函数原型
pid_t wait(int *status);
- 参数
status:代表返回状态,成功调用返回子进程pid,如果没有子
进程调用失败为-1。
- 作用
进程一旦调用了wait,就立即阻塞自己,当子进程结束变成变成僵尸
进程,如果让它找到了这样一个已经变成僵尸的子进程, wait就
会收集这个子进程的信息,并把它彻底销毁后返回;如果没有找到
这样一个子进程,wait就会一直阻塞在这里,直到有一个出现为止.
2、waitpid
- 头文件
#include <sys/types.h>
#include <sys/wait.h>
- 函数原型
pid_t waitpid(pid_t pid,int *status,int options);
- 参数
pid
pid>0时,只等待进程ID等于pid的子进程,不管其它已经有多少子进程运行结束退出了,只要指定的子进程还没有结束,waitpid就会一直等下去。
pid=-1时,等待任何一个子进程退出,没有任何限制,此时waitpid和wait的作用一模一样。
pid=0时,等待同一个进程组中的任何子进程,如果子进程已经加入了别的进程组,waitpid不会对它做任何理睬。
pid<-1时,等待一个指定进程组中的任何子进程,这个进程组的ID等于pid的绝对值。
options
如果不想使用可以设置为0,如果使用了WNOHANG参数调用waitpid,
即使没有子进程退出,它也会立即返回,不会像wait那样永远等下去。
例子
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include <sys/types.h>
#include <errno.h>
#include <sys/wait.h>
#include <string.h>
//有终端信号直接过来了。不影响父进程继续操作
void kill_(int signo){
int mypid;
while(mypid = waitpid(-1, NULL, WNOHANG) >0 ){
printf("my child is [%d]",mypid);
}
}
int main(int argc, char **argv){
pid_t pid;
int status = -1;
signal(SIGCHLD, kill_);
pid = fork();
if(pid <0){
printf("create fork is failed:[%s]",strerror(errno));
}
else if(pid == 0){
//enter child process
printf("chile : raise before\n");
//raise(SIGTSTP);
printf("child : over");
sleep(4);
}
else{
//enter parent process
printf("parent : enter parent process\n");
sleep(3);
printf("patren : over\n");
while(1);
}
}