『阿男的Linux内核世界』*09 wait的使用方法*
我们这篇文章里来写段代码使用wait
函数:
#include <sys/wait.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
int main(int argc, char *argv[]) {
pid_t pid = fork(); // create a child process
if (pid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (pid == 0) { // I am child process
printf("child process sleep for 3 seconds...\n");
sleep(3); // sleep for 3 seconds so parent process needs to wait child process to exit
printf("child process exit.\n");
} else { // I am parent process
printf("parent process waiting for child to exit...\n");
wait(0); // Wait for child process to exit
printf("parent process exit\n");
}
上面这段代码使用fork
函数创建一个child process,然后让child process sleep 5秒;在parent process里,我们使用wait
函数,让parent process等待child process的退出。
编译上面的代码:
$ cc wait.c -o wait
然后执行结果如下:
$ ./wait
parent process waiting for child to exit...
child process sleep for 3 seconds...
child process exit.
parent process exit
从上面的执行过程我们可以看到parent process一定会等child process退出后,自己才退出,这就是wait
函数的作用:确保了进程间的执行顺序。
关于wait
函数的定义:
pid_t wait(int *status);
它的参数status
的含义如下:
If status is not NULL, wait() and waitpid() store status information in the int to which it points.
也就是说,如果我们传入一个非空的status
,那么wait
函数会把执行结束后的child process的一些信息注入到这个status
数据里。注意拿参数当返回值的一部分来使用,是C代码里面的常用技巧,大家可以熟悉一下。关于status
里面具体会有什么信息,我们下次再讲。