关于fork调用输出的困惑

时间:2015-06-03 13:37:51

标签: c

考虑以下程序的输出:

#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

2 个答案:

答案 0 :(得分:4)

你需要检查&#34; fork失败&#34;条件。当fork()返回-1时,发生错误。这是函数语义的一部分,因此如果省略它,将得到不正确的结果。

请参阅一个示例,该示例考虑了fork失败的可能性here

在此related question中查看有关fork可能失败的原因的讨论。

答案 1 :(得分:0)

$只是在流程输出之间显示的提示。因为孩子跑了'#34;脱离&#34;从父级开始,父级可以在子级完成之前返回shell。然后打印提示,然后输出孩子的输出。如果您将所有输出重定向到文件,则$将不在那里。

相关问题