为什么这个全局计数器在 child 过程中没有递减?

Why is this global counter not decrementing in the child process?

在此代码段中(忽略除倒数第二个以外的所有 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

先进入elsecounter还是1,我们wait(NULL)child死。在 if 中备份,fork() 创建 child,但看到 fork() == 0,只有 childcounter 减 1。现在counter 为 0,child 终止于 exit(0)。等待结束,child死了,parent打印出++counter本来应该是0+1=1,突然变成了2,不是1!为什么会这样?

来自 fork 的 Linux 手册页:

Under Linux, fork() is implemented using copy-on-write pages, so the only penalty that it incurs is the time and memory required to duplicate the parent's page tables, and to create a unique task structure for the child.

这意味着无论何时您在父进程或子进程中写入内存,正在写入的页面都会被复制,并且这两个进程最终会得到独立的副本。