324 views
3 3 votes

Assume that every $\texttt{fork()}$ call succeeds.

int main() {
    int a = 0;
    int rc = fork();

    a++;

    if (rc == 0) {
        rc = fork();
        a++;
    } else {
        a++;
    }

    printf("a is %d\n", a);
}

What is the largest value of $\texttt{a}$ printed by the program?

  1. The value may vary because of a race condition
     
  2. $2$
     
  3. $3$
     
  4. None of the above

1 Answer

0 0 votes

After the first $\texttt{fork()}$, the parent and child have separate copies of $\texttt{a}$.

Both processes execute the first increment, making their private value of $\texttt{a}$ equal to $1$.

In the parent:

$\texttt{a++;}$

Therefore, the parent prints $2$.

The first child executes another $\texttt{fork()}$. Both the child and the newly created grandchild then execute:

$\texttt{a++;}$

Their private value also becomes $2$.

Hence, every process prints $2$, and the largest value printed is $2$.

Answer : B

Answer:
Position:
Show:

Related questions

5 5 votes
2 2 answers
473
473 views
GO Classes asked Jul 15
473 views
Consider the following C program. Assume that every $\texttt{fork()}$ call succeeds.int main(void) { unsigned long int i; for (i = 0; i < 6; i++) if (fork() >= 0) continu...
4 4 votes
1 1 answer
318
318 views
GO Classes asked Jul 15
318 views
Assume that every $\texttt{fork()}$ call succeeds.int main() { int pid; pid = fork() && fork(); if (!pid) printf("A\n"); else printf("B\n"); return 0; }How many times are...
5 5 votes
1 1 answer
296
296 views
GO Classes asked Jul 15
296 views
Consider the following program. Assume that every $\texttt{fork()}$ call succeeds.int main() { int p1 = 1, p2 = 2, p3 = 3; p1 = fork(); if (p2 0) p2 = fork(); if (p1 0)...
5 5 votes
2 2 answers
283
283 views
GO Classes asked Jul 15
283 views
Consider the following C program. When the execution reaches line $5$, how many processes and threads, respectively, exist in the process hierarchy?int main() { int i; fo...