Variable modification in a child process
Posted
by
teaLeef
on Stack Overflow
See other posts from Stack Overflow
or by teaLeef
Published on 2014-08-20T20:29:17Z
Indexed on
2014/08/20
22:20 UTC
Read the original article
Hit count: 198
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?
© Stack Overflow or respective owner