C fork调用中的奇怪输出

时间:2016-08-19 05:11:06

标签: c fork

我有以下C代码。

#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>


int main ()
{

    int i=1;

    pid_t child_pid = fork();

    if (child_pid == 0) 
    {
        printf ("%d\n", i++);
        printf ("%d\n", i++);
        printf ("This is child process.");
        return 0;


    }
    else if (child_pid > 0) {
        printf ("%d\n", i++);
        printf ("This is parent process.");
    }

    else {
    printf("Fork failed");
    }

}

我编译了以下内容:gcc testFork.c并通过键入./a.out来运行代码。

我得到的输出是:

vmw_ubuntu@vmwubuntu:~/Desktop/Test C$ ./a.out
1
This is parent process.vmw_ubuntu@vmwubuntu:~/Desktop/Test C$ 1
2
This is child process.

为什么vmw_ubuntu@vmwubuntu:~/Desktop/Test C$出现在不知名的地方?

我只是期待这个输出:

vmw_ubuntu@vmwubuntu:~/Desktop/Test C$ ./a.out
1
This is parent process.1
2
This is child process.

2 个答案:

答案 0 :(得分:4)

因为您没有添加换行符&#39; \ n&#39; printf调用结束时转义字符;因此,当你的父进程返回到你的shell时,shell的提示符为`vmw_ubuntu @ vmwubuntu:〜/ Desktop / Test C $&#39;附在最后。

请记住,当你打电话给&#39; fork&#39;您正在为同一过程创建2个单独的副本。它不再是1个程序,父母可以在孩子面前返回。

编辑:

要获得您想要的输出,您需要拨打“等待快照”的电话。功能。见http://linux.die.net/man/2/wait

答案 1 :(得分:1)

问题可能是printf函数被缓冲:Why does printf not flush after the call unless a newline is in the format string? 禁用缓冲或使用无缓冲的write(..)。 fork没有问题 - 它按指定的方式工作。