2016-08-19 87 views
0

我有以下的C代码。奇怪的输出在C fork调用

#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运行的代码。

我得到的输出是:

[email protected]:~/Desktop/Test C$ ./a.out 
1 
This is parent [email protected]:~/Desktop/Test C$ 1 
2 
This is child process. 

为什么[email protected]:~/Desktop/Test C$出现在中间的地方?

我只是希望这样的输出:

[email protected]:~/Desktop/Test C$ ./a.out 
1 
This is parent process.1 
2 
This is child process. 
+0

一旦父进程结束,shell将恢复;它死的第一件事是打印命令提示符。但是,这个孩子仍然在等待着开始。 – rici

+0

这是你的提示。 –

回答

4

因为你没有添加一个新行“\ n”逃脱你的printf通话结束字符;因此,当你的父进程返回到你的shell时,你的shell`vmw_ubuntu @ vmwubuntu:〜/ Desktop/Test C $'的提示被添加到最后。

请记住,当您调用'fork'时,您正在创建2个单独的同一过程的副本。它不再是一个程序,父母可以在孩子面前回来。

编辑:

达到你想要的输出,你需要插入到“waitpid函数”函数的调用。请参阅http://linux.die.net/man/2/wait