到目前为止,我们没有做太多事情:只是创建了一个子进程,打印了一些信息并退出。事实表明,有时候父进程需要等待子进程执行完毕,这很有用。这项任务由wait()系统调用(或者更完整的兄弟接口waitpid())。图5.2 展示了更多细节。
clude <stdio.h>
clude <stdlib.h>
clude <unistd.h>
clude <sys/wait.h>
int
main(int argc, char *argv[])
{
printf("hello world (pid:%d)\n", (int) getpid());
int rc = fork();
if (rc < 0) { // fork failed; exit
fprintf(stderr, "fork failed\n");
exit(1);
} else if (rc == 0) { // child (new process)
printf("hello, I am child (pid:%d)\n", (int) getpid());
} else { // parent goes down this path (main)
int wc = wait(NULL);
printf("hello, I am parent of %d (wc:%d) (pid:%d)\n",
rc, wc, (int) getpid());
}
return 0;
}
图5.2 调用fork()和wait()(p2.c)
在p2.c 的例子中,父进程调用wait(),延迟自己的执行,直到子进程执行完毕。当子进程结束时,wait()才返回父进程。
上面的代码增加了wait()调用,因此输出结果也变得确定了。这是为什么呢?想想看。(等你想想看……好了)
下面是输出结果:
prompt> ./p2
hello world (pid:29266)
hello, I am child (pid:29267)
hello, I am parent of 29267 (wc:29267) (pid:29266)
prompt>
通过这段代码,现在我们知道子进程总是先输出结果。为什么知道?好吧,它可能只是碰巧先运行,像以前一样,因此先于父进程输出结果。但是,如果父进程碰巧先运行,它会马上调用wait()。该系统调用会在子进程运行结束后才返回1。因此,即使父进程先运行,它也会礼貌地等待子进程运行完毕,然后wait()返回,接着父进程才输出自己的信息。
-
有些情况下,wait()在子进程退出之前返回。像往常一样,请阅读man 手册获取更多细节。小心本书中绝对的、无条件的陈述,比如“子进程总是先输出结果”或“UNIX 是世界上最好的东西,甚至比冰淇淋还要好”。 ↩