首页 > 技术文章 > wait函数

scu-cjx 2017-10-24 15:31 原文

当一个进程正常或异常终止时,内核就向其父进程发送SIGCHLD信号。子进程终止是一个异步事件(其能够在父进程运行的任何时候发生)。

对于wait(),其调用者,即父进程可以有如下状态:

  • 如果其所有子进程都还在运行,则阻塞;
  • 如果一个子进程已终止,正等待父进程获取其终止状态,则取得该子进程的终止状态后立即返回;
  • 如果它没有任何子进程,则立即出错返回;

代码测试:

 1 #include <stdio.h>
 2 #include <unistd.h>
 3 #include <stdlib.h>
 4 
 5 int main(void)
 6 {
 7     pid_t pid_f = getpid();
 8     pid_t pid_c;
 9     pid_f = fork();
10     if(pid_f < 0) {
11         printf("fork error\n");
12     }
13     else if(pid_f == 0) {
14         printf("child process start\n");
15         sleep(10);
16     }
17     else {
18         printf("father process goes on\n");
19         wait(NULL);
20         printf("child process exited\n");
21     }
22     printf("wait for child exit %d\n",pid_f);
23     return 0;
24 }

执行结果:

最初执行:

root@ubuntu:/home/test# ./wait_test
father process goes on
child process start

 父进程创建子进程后,调用wait(),发生阻塞,等待一个子进程退出;子进程休眠10秒后执行后续操作。

10秒后:

root@ubuntu:/home/test# ./wait_test
father process goes on
child process start
wait for child exit 0
child process exited
wait for child exit 6038

子进程休眠结束后,输出“wait for child exit 0”,其进程号表明其为子进程输出结果。父进程输出“wait for child exit 6038”,其进程号表明其为父进程输出结果。

推荐阅读