以下代码:
B() {
pid_t pid;
if ((pid=fork())!= 0)
waitpid(pid,NULL,0);
printf("2 ");
if (fork() == 0)
{ printf("3 "); exit(0); }
printf("5 ");
exit(0);
}
可以有一个输出:我不确定哪个是正确的输出。
232553
235325
232355
235253
252533
这 2 行意味着如果 PID 是父级,那么等待什么?
if ((pid=fork())!= 0)
waitpid(pid,NULL,0);
那么如果是子进程(fork = 0),那么打印 3.. 对吗?
if (fork() == 0)
{ printf("3 "); exit(0); }
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 的一些排列组成。没有一个输出是正确的,因为输出取决于进程执行的顺序,这是任意的。
waitpid
函数等待子函数终止。你说的其他一切都是正确的。像这样的程序没有一个正确的输出,因为它取决于进程执行的顺序,这是任意的。
if ((pid=fork())!= 0)
waitpid(pid,NULL,0);
好的,所以现在父母将等待孩子终止。
printf("2 ");
孩子将立即输出 2。父级将在子级终止后的一段时间内输出 2。
if (fork() == 0)
{ printf("3 "); exit(0); }
父项和子项都将分叉。他们的两个孩子都将打印 3 并退出。
printf("5 ");
父项和原始子项都将打印 5。
exit(0);
父级和口型都将刷新其输出缓冲区并终止。