2012-11-29 36 views
2

我爲了使不同proccesses運行,但打印的代碼counfuses我一個簡單的message.The結果使用fork()..看看代碼:fork()和標準錯誤與終端

#include <stdlib.h> 
#include <stdio.h> 
#include <unistd.h> 
#include <errno.h> 
#include <math.h> 
#include <sys/types.h> 
#include <sys/ipc.h> 
#include <sys/sem.h> 
#include <time.h> 


int main(void) 
{ 

    fork(); 
    fork(); 
    fork(); 
    fprintf(stderr,"hello world\n"); 

} 

,輸出爲:

[email protected]:~/OS$ ./main 
hello world 
hello world 
hello world 
hello world 
hello world 
hello world 
[email protected]:~/OS$ hello world 
hello world 

[email protected]:~/OS$ 

請注意,我在終端的第一行執行程序,但輸出是不是我的預期。請幫幫我!提前致謝!如果fprintf用printf(「......」)改變,也會發生同樣的情況

編輯:我不明白爲什麼打印是這種方式。在終端線旁邊有6個,之後有1個...

+0

你看過'fork'函數的工作原理嗎?嘗試猜猜爲什麼你使用3把叉子8次'hello world'。提示,8 = 2^3。 –

+0

我知道這個事實!我的問題不是8打印,而是它們被終端命令打亂。我不覺得它合理的程序打印6之前,終端線(馬里奧@ Ubuntu的:〜/ OS $你好世界)旁邊和一個.. – JmRag

回答

3

當父程序退出時,運行父程序的shell會在屏幕上打印shell提示符[email protected]:~/OS$。在提示後,將打印任何尚未打印的子程序hello world。如果您希望提示不出現在所有hello world之前,則需要讓父母等待所有子和孫程序終止。

檢查this看看如何讓父母等待。

+0

Thx很多!這真的讓我擺脫了許多麻煩! – JmRag

0

您正在創建8個進程。每個fork將該過程分成兩部分。它的原始父節點完成了我仍在執行的其他進程。因此,如果原始進程完成執行,shell會執行並打印提示,儘管其他進程仍在執行。