3

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?

DoxyLover
  • 3,366
  • 1
  • 15
  • 19
teaLeef
  • 1,879
  • 2
  • 16
  • 26

1 Answers1

5

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.

meaning-matters
  • 21,929
  • 10
  • 82
  • 142