這有點像......
1 (main) instance, i = 0(unforked)
fork() > 2 instances, with i's = 0(forked), and 0(forked)
0 output from main instance, increments its i, 2 instances with i = 1u, 0f
main instance forks, there's 3 instances with i's 1f, 1f, 0f
1 output from main instance, increments its i, 3 instances with i = 2u, 1f, 0f
main instance forks, there's 4 instances with i's 2f, 2f, 1f, 0f
2 output from main instance, increments its i, 4 instances with i = 3u, 2f, 1f, 0f
main instance then dies, 3 instances with i = 2f, 1f, 0f
2 output from next instance, increments its i, 3 instances with i = 3u, 1f, 0f
next instance then dies, 2 instances with i = 1f, 0f
1 output from next instance, increments its i to 2, 2 instances with i = 2u, 0f
...等
的順序進程正在輸出,但未確定,所以您可能不會每次都看到完全相同的輸出,即使這樣做也不是您可以保證的。
正如其他人所說,每個進程都有自己的全局「我」,它跟蹤,它的價值僅僅是分叉過程中我的分叉值。
你還沒有告訴我們你不喜歡這件事。 – bmargulies 2010-01-28 22:15:01
我不喜歡,因爲我不明白什麼時候我們會增加父進程或子進程中的fork。通常,如果我們想在子進程中增加,我們可以這樣做(fork()== 0)++ i;但是當我們這樣做時,我會在中間有點失落! – Bruno 2010-01-28 22:20:12
按照答案:孩子增加孩子,父母增加父母,從來沒有兩個孩子會。 – bmargulies 2010-01-29 01:13:44