2016-08-19 75 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