Consider the following code fragment: if (fork() == 0) { a = a + 5;…
2005
Consider the following code fragment:
if (fork() == 0)
{
a = a + 5;
printf("%d,%d\n", a, &a);
}
else
{
a = a - 5;
printf("%d, %d\n", a, &a);
}Let u, v be the values printed by the parent process, and x, y be the values printed by the child process. Which one of the following is TRUE?
Answer: C. u + 10 = x and v = y — Concept: After fork(), the child process is a near-exact duplicate of the parent — both share the same virtual address-space layout, so a given variable has…
- A.
u = x + 10 and v = y
- B.
u = x + 10 and v != y
- C.
u + 10 = x and v = y
- D.
u + 10 = x and v != y
Attempted by 124 students.
Show answer & explanation
Correct answer: C
Concept: After fork(), the child process is a near-exact duplicate of the parent — both share the same virtual address-space layout, so a given variable has the SAME virtual address in parent and child. However, from the instant fork() returns, each process holds its own independent copy of that variable’s value: a write in one process never affects the other’s copy. fork() returns 0 in the child and the child’s process ID in the parent.
Application: Trace this fragment using that rule.
Since fork() returns 0 only in the child, the child takes the if-branch (a = a + 5) and the parent takes the else-branch (a = a - 5).
Let A0 be the value of a immediately before fork() returns (both processes start from this same value).
Child: a becomes A0 + 5, so the child prints x = A0 + 5.
Parent: a becomes A0 - 5, so the parent prints u = A0 - 5.
Subtracting, x - u = (A0 + 5) - (A0 - 5) = 10, i.e. u + 10 = x — this holds for every value of A0.
Both branches also print &a. Per the Concept, the two processes retain the same virtual address for a, so the value printed for &a is identical in both: v = y.
Cross-check: Take a concrete value, say A0 = 20. The parent computes u = 20 - 5 = 15 and the child computes x = 20 + 5 = 25. Check: u + 10 = 15 + 10 = 25 = x — the relation holds, and it does so regardless of which value A0 actually is, so no additional information about a’s initial value is needed.
Conclusion: u + 10 = x and v = y.
Note: printing a pointer with %d (rather than %p) is technically undefined behavior in C; however, this is the exact code as set in the original exam, and every archived derivation of this question treats the value printed for &a as the address value, so the relation v = y is the intended and universally accepted reading.
A video solution is available for this question — log in and enroll to watch it.
Explore the full course: Iocl Engineers Officers Grade A Paper 2