2014-09-05 39 views
0

該程序有很多叉如下沒有完成爲什麼我的許多叉子程序不停止?

#include <unistd.h> 
#include <iostream> 

int main() { 
    static int fork_cnt = 0; 
    const unsigned kCnt = 4; 

    for (int i = 0; i < kCnt; ++i) { 
    fork(); 
    } 
    std::cout << "fork_cnt=" << fork_cnt << std::endl; 
    return 0; 
} 

當我跑了它,它停止如下。看來主叉完成了,但其他程序正在等待某些東西。

fork_cnt=0 
[email protected]:~$ fork_cnt=0 
fork_cnt=0 
fork_cnt=0 
fork_cnt=0 
fork_cnt=0 
fork_cnt=0 
fork_cnt=0 
fork_cnt=0 
fork_cnt=0 
fork_cnt=0 
fork_cnt=0 
... 

回答

1

其實這個程序並沒有等待任何東西。這裏發生的是你創建的子進程,從你當前的stdin分離(至少我相信他們確實給出了他們的行爲)。當您的原始過程返回時,sh重新獲得對stdin的控制權並提示您輸入 - 因此您的第二個列表的第二行中爲[email protected]:~$。無論如何,你的子進程繼續寫入標準輸出,因此在[email protected]:~$之後輸出fork_cnt=0。當所有進程結束時sh看不到任何理由再次提示您輸入,因此在您看來,程序仍在運行,但如果您輸入了某個命令(或者只是點擊Enter),您就會看到它的確如此。

要測試此操作,請嘗試以下操作:在每個子進程創建後立即創建一個無限循環。

#include <unistd.h> 
#include <iostream> 

int main() { 
    static int fork_cnt = 0; 
    const unsigned kCnt = 4; 

    for (int i = 0; i < kCnt; ++i) { 
    int pid = fork(); 
    while(pid == 0); 
    } 
    std::cout << "fork_cnt=" << fork_cnt << std::endl; 
    return 0; 
} 

現在fork_cnt=0輸出只有一次,你恢復對終端的控制。

[email protected]:~/Programming/playground/fork# ./a.out 
fork_cnt=0 
[email protected]:~/Programming/playground/fork# 

不管怎樣,子進程仍然在運行,你可以很容易地在你的shell進入ps驗證。

相關問題