甲執行while循環運行,直到在括號內的條件是假的。在這種情況下,這將是:直到fork()
的返回值不等於0。
fork()
的回報是:
成功時,子進程的PID在父返回,並且在孩子中返回0。失敗時,在父項中返回-1,不創建子進程,並且適當地設置errno。
所以一旦fork成功執行有2個進程(父和一個新的子進程)。其中一個將返回0(子進程),另一個(父進程)將返回一些其他值(子進程的PID)。
因此,這告訴你,代碼永遠運行,因爲每個子進程將繼續執行while()循環。
說你的父母是PID = 0 †,第一個孩子是PID = 1 †等代碼的第一次運行會是這樣的:
while(fork()==0) // now there are two processes, the child which returns 0 and the
{ // parent which returns 1 (the new child's pid)
if(fork() == 0) break; // this code is now only executed by the child (1) as the
// parent already left the while loop since it's return was
// not == 0
// once this code executes there are 2 processes running
// child(1) will return child(2)'s PID, child(2) will
// return 0 and will enter the if and break from the loop
// now here it's only the original child(1) running again
}
所以你最終了類似:
0 is the original parent, it makes a child and leaves
1 is the original child, it creates a child(2) and then goes to the while loop again
where it generates 3 before leaving
2 is the child of 1 where it leaves because of the break in the if
3 now hits the if and generates 4 (which leaves because of the break)
3 now goes back to while and generates 5 then leaves,
etc
etc
+--> 4
|
| (if)
|
0 --> 1 -+--> 3 ---> 5
|
|(if)
|
+--> 2
† - 這些都是不現實的PID,同時運行在任何現代的Linux發行版的用戶空間代碼來獲得,但他們更容易閱讀,然後真正的RANDO m字符串,所以我正在使用它們。
它被稱爲兩次。 – Shark 2013-04-30 12:35:12
請參閱「叉炸彈」。 – paxdiablo 2013-04-30 12:36:22
fork()在調用進程中返回子進程的PID,在子進程中返回0。所以它會繼續產生子進程,這會自己產生一個子進程。對? :) – Shark 2013-04-30 12:38:40