我正在研究 Bryant 和 O'Hallaron 的Computer Systems, A Programmer's Perspective
. 练习 8.16 要求一个程序的输出,比如(我改变了它,因为他们使用了一个你可以在他们的网站上下载的头文件):
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>
int counter = 1;
int main()
{
if (fork() == 0){
counter--;
exit(0);
}
else{
Wait(NULL);
printf("counter = %d\n", ++counter);
}
exit(0);
}
我回答“counter = 1”是因为父进程等待其子进程终止,然后递增计数器。但孩子首先减少它。然而,当我测试程序时,我发现正确的答案是“counter = 2”。子进程和父进程中的变量“计数器”是否不同?如果不是,那为什么答案是 2?