What is the output of the following program? main( ) { int a = 10; if ((fork (…

2017

What is the output of the following program?

main( )
{
int a = 10;
if ((fork ( ) == 0))
a++;
printf (“%d\\n”, a );
} 
  1. A.

    10 and 11

  2. B.

    10

  3. C.

    11

  4. D.

    11 and 11

Attempted by 164 students.

Show answer & explanation

Correct answer: A

The fork() system call creates a new child process. In the parent process, fork() returns the child's PID (non-zero), so the if condition is false and 'a' remains 10. In the child process, fork() returns 0, so the if condition is true and 'a' increments to 11. Both processes continue execution after the if block, meaning both execute printf(). Consequently, two lines are printed: 10 and 11.

Explore the full course: Isro