Skip to main content

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

GATE CSE 2024 PYQ: Consider the following code snippet using the fork () and wait () system calls. Assume that the code…

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.
 

  1. int x=3;
  2.  
  3. while (x>0){
  4.  
  5. fork ();
  6.  
  7. printf("hello");
  8.  
  9. wait (NULL) ;
  10.  
  11. X-- ;
  12.  
  13. }

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

    Answer

    14

    Approach

    Count the total number of printf executions by recursively summing over each process's remaining loop iterations. A process with x=k executes k iterations/prints, and it forks one child at each of its iterations (values k,k-1,...,1). wait() may serialize execution but does not change the total count.

    The initial process has x=3 (using x-- as intended), so the total number of printf executions is F(3)=14. Each fork creates an independent copy of x, and each created child still executes the printf for the current iteration before decrementing x.

    Reviewed by GateIQ Editorial Team: IIT & IISc Alumni.