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!這是爲什麼?
相關:[數據共享之間的進程,當我們在C中使用叉](http://stackoverflow.com/questions/32901590/is-data-shared-between-processes-when-we-use-fork-in -C) –