以下代码:
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这两行意味着如果pid是父进程,那么等待什么?
if ((pid=fork())!= 0)
waitpid(pid,NULL,0); 如果是子进程(fork = 0),则打印3..对,是这样?
if (fork() == 0)
{ printf("3 "); exit(0); }发布于 2012-12-10 06:45:25
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);
}正如David Schwartz所说,这个程序的输出将由数字2、3和5的某种排列组成。没有一个输出是正确的,因为输出取决于进程执行的顺序,这是任意的。
发布于 2012-12-10 06:43:37
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);父级和原始子级都将刷新其输出缓冲区并终止。
https://stackoverflow.com/questions/13792631
复制相似问题