Tracing a global variable through nested fork and wait

Assume the usual headers are included and every call to fork succeeds. The program below runs from a terminal, and each printf line appears as soon as it is called.


C
int x = 1;

int main(void) {
    if (fork() == 0) {
        x += 4;
        if (fork() == 0) {
            x *= 3;
            printf("G %d\n", x);
            exit(0);
        }
        wait(NULL);
        x -= 1;
        printf("C %d\n", x);
        exit(0);
    }
    wait(NULL);
    x *= 10;
    printf("P %d\n", x);
    return 0;
}


Here P is the original process, C is its child and G is the child's own child. For each process, enter the value of x it prints and the position of its line in the output, using 1 for the first line, 2 for the second and 3 for the third.

ProcessValue of x printedPosition in output
P (original parent)
C (first child)
G (grandchild)

Create a free account to get started

Unlock full course notes by signing up

  • Video lessons taught by top educators
  • Practice questions with guided solutions
  • Written review notes for reference
  • Expert answers anytime from course tutors

More Concurrent Programs Questions: