Skip to content
Official PYQ · 2024

GATE CS 2024 Set 1 Q47 — System Calls

Explain with AI

Consider the following code snippet using the fork () and wait () system calls. Assume that the code compiles and runs correctly, and that the system calls run successfully without any errors.
 

int x=3;

while (x>0){

fork ();

printf("hello");

wait (NULL) ;

X-- ;

}

The total number of times the printf statement is executed is __________.

View worked solution

Answer: 14

Let T(x)T(x) be the total number of times the printf statement is executed by a process and all its descendants starting from the loop iteration with value xx.

When a process starts an iteration with value xx:

  1. It calls fork(), creating a child process. Both parent and child now have the same value of xx.
  2. Both processes execute printf("hello"), contributing 22 prints.
  3. Both processes call wait(NULL):
    • The child process has no children yet, so its wait() returns immediately. It decrements xx to x−1x-1 and proceeds to run to completion, contributing T(x−1)T(x-1) prints.
    • The parent process waits for the child to terminate completely. Once the child terminates, the parent's wait() returns. The parent then decrements xx to x−1x-1 and proceeds to run to completion, contributing T(x−1)T(x-1) prints.

This gives us the recurrence relation:

T(x)=2+2⋅T(x−1)for x>0T(x) = 2 + 2 \cdot T(x-1) \quad \text{for } x > 0

With the base case T(0)=0T(0) = 0 (since the loop condition x>0x > 0 is false), we compute:

  • T(1)=2+2⋅T(0)=2+0=2T(1) = 2 + 2 \cdot T(0) = 2 + 0 = 2
  • T(2)=2+2⋅T(1)=2+2(2)=6T(2) = 2 + 2 \cdot T(1) = 2 + 2(2) = 6
  • T(3)=2+2⋅T(2)=2+2(6)=14T(3) = 2 + 2 \cdot T(2) = 2 + 2(6) = 14

Thus, the total number of times the printf statement is executed is 14.

Free practice · Your answers on this page are not saved.

Published
Report a correction
Keep exploringMore System Calls questions