簡體   English   中英

以下fork程序的輸出是什么?

[英]What is the output of the following fork program?

int main() {
int p1, p2;
printf("A\n"); // we always print A first
p1 = fork();

if (p1 == 0) { // child
    printf("B\n"); 

    p2 = fork(); // fork

    if (p2 == 0) {
        sleep(2);
        printf("C\n");
        exit(0);
    }
    wait(0); // parent waits for child to finish
}
printf("D\n"); 
exit(0);


return 0;
}

我得到的輸出如下:

A // always first

B or D // whether we are in parent or child. Program may be terminated here

C // always since parent of p2 waits

D // since p2 parent exits if condition, prints D, then exits(0)

我已經運行了100次,並且總是得到ABD ... terminate ... CD “ D”總是在“ B”之前。 這是隨機的還是我看不到的原因?

謝謝。

確切的輸出完全取決於操作系統如何調度每個進程。 父母與第一個孩子之間沒有同步,因此“ B”和“ D”可以按任何順序打印。

例如,在我的機器上,我得到“ ADB(最終)CD”。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM