函数原型:
#include<sys/types.h>
#include<sys/wait.h>
pid_t wait(int *status);
进程一旦调用了wait就立即阻塞自己,由wait自动分析是否当前进程的某个子进程已经退出,如果让它找到了这样一个已经变成僵尸的子进程,wait就会收集这个子进程的信息,并把它彻底销毁后返回;如果没有找到这样一个子进程,wait就会一直阻塞在这里,直到有一个出现为止。
参数status用来保存被收集进程退出时的一些状态,它是一个指向int类型的指针。但如果我们对这个子进程是如何死掉毫不在意,只想把这个僵尸进程消灭掉,(事实上绝大多数情况下,我们都会这样想),我们就可以设定这个参数为NULL,就像下面这样:
pid = wait(NULL);
如果成功,wait会返回被收集的子进程的进程ID,如果调用进程没有子进程,调用就会失败,此时wait返回-1,同时errno被置为ECHILD。
例子:
/*wait.c*/
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
int main()
{
printf("create child prcocess error: %s\n", strerror(errno));
如果是子进程 */
printf("I am child process with pid %d \n", getpid());
printf("Now in parent process, pid = %d\n", getpid());
printf("I am waiting child process to exit.\n");
在这里等待子进程结束 */
printf("I catched a child process with pid of %d\n", pr);
printf("error: %s\n.\n", strerror(errno));
}
[root@super liuxl]# gcc wait.c -o wait
I am child process with pid 20129
Now in parent process, pid = 20128
I am waiting child process to exit.
I catched a child process with pid of 20129
可以明显注意到,在第2行结果打印出来前有10秒钟的等待时间,这就是我们设定的让子进程睡眠的时间,只有子进程从睡眠中苏醒过来,它才能正常退出,也就才能被父进程捕捉到。其实这里我们不管设定子进程睡眠的时间有多长,父进程都会一直等待下去。
如果参数status的值不是NULL,wait就会把子进程退出时的状态取出并存入其中,这是一个整数值(int),指出了子进程是正常退出还是被非正常结束的,以及正常结束时的返回值,或被哪一个信号结束的等信息。由于这些信息被存放在一个整数的不同二进制位中,所以用常规的方法读取会非常麻烦,人们就设计了一套专门的宏(macro)来完成这项工作,下面我们来学习一下其中最常用的两个:
1,WIFEXITED(status) 这个宏用来指出子进程是否为正常退出的,如果是,它会返回一个非零值。
(请注意,虽然名字一样,这里的参数status并不同于wait唯一的参数–指向整数的指针status,而是那个指针所指向的整数,切记不要搞混了。)
2, WEXITSTATUS(status) 当WIFEXITED返回非零值时,我们可以用这个宏来提取子进程的返回值,如果子进程调用exit(5)退出,WEXITSTATUS(status) 就会返回5;如果子进程调用exit(7),WEXITSTATUS(status)就会返回7。请注意,如果进程不是正常退出的,也就是说, WIFEXITED返回0,这个值就毫无意义。
/*wait2.c*/
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
int main()
{
子进程 */
printf("This is child process with pid of %d.\n", getpid());
如果WIFEXITED返回非零值 */
printf("The child process %d exit normally.\n", pr);
printf("the return code is %d.\n", WEXITSTATUS(status));
printf("The child process %d exit abnormally.\n", pr);
}
[root@super liuxl]# gcc wait2.c -o wait2
[root@super liuxl]# ./wait2
This is child process with pid of 20253.
The child process 20253 exit normally.
the return code is 3.
当然,处理进程退出状态的宏并不止这两个,但它们当中的绝大部分在平时的编程中很少用到,有兴趣的读者可以参阅Linux man pages。