Variable modification in a child process

我怕爱的太早我们不能终老 提交于 2021-01-27 16:46:37

问题


I am working on Bryant and O'Hallaron's Computer Systems, A Programmer's Perspective. Exercise 8.16 asks for the output of a program like (I changed it because they use a header file you can download on their website):

#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);
}

I answered "counter = 1" because the parent process waits for its children to terminate and then increments counter. But the child first decrements it. However, when I tested the program, I found that the correct answer was "counter = 2". Is the variable "counter" different in the child and in the parent process? If not, then why is the answer 2?


回答1:


Your parent process starts with counter at 1.

Then it waits for the forked child process to finish.

(Whatever happens in the forked process, does not affect the parent's version of counter. Each process has its own memory space; no variables are shared.)

And, finally the printf() statement first increments counter with the ++ operator, this makes counter get the value 2.



来源:https://stackoverflow.com/questions/25413868/variable-modification-in-a-child-process

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!