问题
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