C 为什么这个全局计数器在子进程中不递减?

C 为什么这个全局计数器在子进程中不递减?,c,process,fork,parent-child,C,Process,Fork,Parent Child,在这段代码中,(除了倒数第二个之外,忽略所有的printfs),我希望计数器到最后都是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); }

在这段代码中,(除了倒数第二个之外,忽略所有的
printf
s),我希望
计数器到最后都是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
计数器仍然为1,我们
等待(NULL)
死亡。在
中备份如果
fork()
创建子对象,但如果
fork()==0
,则只有
子对象将
计数器减量1。现在,
计数器
为0,
子项
终止于
出口(0)
。等待结束,
child
已死亡,
parent
打印
++counter
,该值应为0+1=1,但突然变为2,而不是1!为什么会这样?

来自
fork
的Linux手册页:

在Linux下,fork()是使用copy-on-write页实现的,因此它带来的唯一损失是复制父级的页表以及为子级创建唯一的任务结构所需的时间和内存

这意味着,每当您在父进程或子进程中写入内存时,将复制正在写入的页面,这两个进程将以独立副本结束。

相关: