简体   繁体   English

关于派生调用输出的困惑

[英]Confusion about output of fork calls

Consider the output of the below program: 考虑以下程序的输出:

#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);
}

The output that I expected is: 我期望的输出是:

This is the son process, a = 4;
This is the dad process, a = 6;

But I got the output as: 但是我得到的输出为:

This is the son process, a = 4

So why the parent process did not execute the printf ? 那么,为什么父进程没有执行printf呢? How can i get the output i want? 如何获得我想要的输出?

Update: 更新:

Just now I tried once more, output like this: 刚才我再次尝试,输出如下:

$ gcc fork.c -o fork
$ ./fork
This is the dad process, a = 6
$ This is the son process, a = 4

Now there is still a problem: why is there a $ between two lines of output? 现在仍然存在一个问题:为什么两行输出之间有一个$

I think the expected output should be like this: 我认为预期的输出应该是这样的:

$ gcc fork.c -o fork
$ ./fork
This is the dad process, a = 6
This is the son process, a = 4

I can't figure out why $ is there. 我不知道为什么有$

More details: 更多细节:

gcc version: gcc 4.8.2  
OS: ubuntu 14.04

You need to check the "fork failed" condition. 您需要检查“分叉失败”情况。 When fork() returns -1, an error happened. 当fork()返回-1时,发生错误。 This is part of the semantics of the function, so if you omit it, you will get incorrect results. 这是函数语义的一部分,因此,如果省略它,将会得到错误的结果。

See an example which takes into account the possibility of fork failing here . 请参阅此处的示例,其中考虑了fork失败的可能性。

See a discussion of why fork could fail in this related question . 请参阅有关fork为何在此相关问题中失败的讨论。

The $ is just the prompt that is displaying in between the process output. $只是在过程输出之间显示的提示。 Because the child runs "detached" from the parent, the parent may return to the shell before the child has finished. 因为子级与父级“分离”运行,所以父级可能会在子级完成之前返回外壳。 So the prompt is printed, then the child's output. 因此,将打印提示,然后输出孩子的输出。 If you would redirect all output to a file, the $ will not be in there. 如果将所有输出重定向到文件,则$不会在其中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM