Skip to main content

GATE CSE 2005Operating System › Process Concepts, Threads & System CallsVerified

GATE CSE 2005 PYQ: Consider the following code fragment : if ( fork () == 0 ) { a = a + 5 ; printf ( "%d, %p n" , a , & a ); }…

Consider the following code fragment:
if (fork() == 0)
{
   a = a + 5;
   printf("%d, %p n", a, &a);
}
else
{
   a = a - 5;
   printf ("%d, %p n", a,& a);
}

Let u,vu,v be the values printed by the parent process and x,yx,y be the values printed by the child process. Which one of the following is TRUE?

  1. A
    u=x+10 and v=yu = x + 10 \text{ and } v = y
  2. B
    u=x+10 and v!=yu = x + 10 \text{ and } v != y
  3. C
    u+10=x and v=yu + 10 = x \text{ and } v = y
    Correct answer
  4. D
    u+10=x and v!=yu + 10 = x \text{ and } v != y

Answer

(C) u + 10 = x and v = y u + 10 = x \text{ and } v = y u + 10 = x and v = y

Approach

Apply fork() semantics: the child process starts with a copy of the parent's address space. Let the value of a just before fork be $a_0$. The parent executes the else branch and prints $u = a_0 - 5$ and address $v = \&a$. The child executes the if branch and prints $x = a_0 + 5$ and address $y = \&a$. Since $x = a_0 + 5$ and $u = a_0 - 5$, we get $x = u + 10$. Also, because fork copies the parent's virtual-address layout, the logical address of a is the same in both processes, so $v = y$.

The child adds 5 while the parent subtracts 5 from the same initial copied value. Thus child value $x$ is exactly 10 more than parent value $u$: $x = u + 10$. Since fork preserves the virtual-address layout, the printed logical addresses are equal: $v = y$. Therefore option C is correct.

Reviewed by GateIQ Editorial Team: IIT & IISc Alumni.