2016-03-02 74 views
1

在這段代碼中,(除了第二個以外忽略了所有的printf),我預計counter到最後時爲1。爲什麼這個全局計數器在子進程中不會遞減?

int counter = 1; //GLOBAL! 

int main() 
{ 
    if (fork() == 0) { 
     printf("child has spoken!\n"); 
     counter--; 
     printf("and counter is now: %d\n", counter);  
     exit(0); 
    } 
    else { 
     printf("what is counter here?: %d\n", counter); 
     printf("now we'll wait\n"); 
     wait(NULL); 
     printf("we've waited long enough!\n"); 
     printf("counter = %d\n", ++counter); 
     printf("counter is 2????: %d\n", counter); 
    } 
    exit(0); 
} 

該過程可以看出打印輸出的內容。

what is counter here?: 1 
now we'll wait 
child has spoken! 
and counter is now: 0 
we've waited long enough! 
counter = 2 
counter is 2????: 2 

else第一次進入,counter仍處於1,wait(NULL)爲我們的child死亡。在if備份,fork()創建子,但看到fork() == 0,只有child遞減counter 1。現在counter爲0,child終止於exit(0)。等待結束,child已死,parent打印++counter應該是0 + 1 = 1,但突然它是2,而不是1!這是爲什麼?

+1

相關:[數據共享之間的進程,當我們在C中使用叉](http://stackoverflow.com/questions/32901590/is-data-shared-between-processes-when-we-use-fork-in -C) –

回答

2

從Linux手冊頁fork

在Linux下,fork()的使用寫入時複製頁面實現的,所以它會帶來唯一的懲罰是複製所需的時間和內存父母的頁面表,併爲孩子創建一個獨特的任務結構。

這意味着,無論是在父進程還是子進程中寫入內存,正在寫入的頁面都將被複制,並且兩個進程結束時都有獨立的副本。

相關問題