B() {
pid_t pid;
/* On success, fork() returns 0 to the child. It returns the child's process
* ID to the parent. So this block of code, executes a fork(), and has the
* parent wait for the child.
* Amusing sidenote: if the fork() fails, the parent will wait for *any*
* child process, since the return will be -1.
*/
if ((pid=fork())!= 0)
waitpid(pid,NULL,0);
/* Both the parent and the child will print 2. The parent, will, of course,
* only print 2 after the child exits, because of the waitpid above.
*/
printf("2 ");
/* Now we fork again. Both the parent and the child from the previous fork will
* fork again, although the parent will do it *after* the child exit. The resulting
* child process will print a single 3 and then exit.
*/
if (fork() == 0)
{ printf("3 "); exit(0); }
/* Now both the parent and the child print a 5 and exit */
printf("5 ");
exit(0);
}
正如大卫施瓦茨所说,这个程序的输出将由数字 2、3 和 5 的一些排列组成。没有一个输出是正确的,因为输出取决于进程执行的顺序,这是任意的。