[英]Confusion about output of fork calls
考虑以下程序的输出:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
void main()
{
pid_t pid;
int a = 5;
pid = fork();
if (pid == 0)
printf("This is the son process, a = %d\n", --a);
else
printf("This is the dad process, a = %d\n", ++a);
}
我期望的输出是:
This is the son process, a = 4;
This is the dad process, a = 6;
但是我得到的输出为:
This is the son process, a = 4
那么,为什么父进程没有执行printf呢? 如何获得我想要的输出?
更新:
刚才我再次尝试,输出如下:
$ gcc fork.c -o fork
$ ./fork
This is the dad process, a = 6
$ This is the son process, a = 4
现在仍然存在一个问题:为什么两行输出之间有一个$
?
我认为预期的输出应该是这样的:
$ gcc fork.c -o fork
$ ./fork
This is the dad process, a = 6
This is the son process, a = 4
我不知道为什么有$
。
更多细节:
gcc version: gcc 4.8.2
OS: ubuntu 14.04
$
只是在过程输出之间显示的提示。 因为子级与父级“分离”运行,所以父级可能会在子级完成之前返回外壳。 因此,将打印提示,然后输出孩子的输出。 如果将所有输出重定向到文件,则$
不会在其中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.