【问题标题】:Why is this global counter not decrementing in the child process?为什么这个全局计数器在子进程中没有递减?
【发布时间】: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,只有childcounter 递减1。现在counter 为0,child 终止于exit(0)。等待结束,child 死了,parent 打印出++counter,它应该是 0 + 1 = 1,但突然变成了 2,而不是 1!为什么会这样?

【问题讨论】:

标签: c process fork parent-child


【解决方案1】:

来自fork 的 Linux 手册页:

在 Linux 下,fork() 是使用写时复制页实现的,因此它所招致的唯一损失是复制父页表以及为子页创建独特的任务结构所需的时间和内存。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-05-15
    • 1970-01-01
    • 2022-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-12-09
    相关资源
    最近更新 更多