【发布时间】:2016-06-15 18:34:58
【问题描述】:
在这个 sn-p 中,(忽略除倒数第二个之外的所有 printfs),我希望 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 process fork parent-child