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 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 .
When a process starts an iteration with value :
- It calls
fork(), creating a child process. Both parent and child now have the same value of . - Both processes execute
printf("hello"), contributing prints. - Both processes call
wait(NULL):- The child process has no children yet, so its
wait()returns immediately. It decrements to and proceeds to run to completion, contributing prints. - The parent process waits for the child to terminate completely. Once the child terminates, the parent's
wait()returns. The parent then decrements to and proceeds to run to completion, contributing prints.
- The child process has no children yet, so its
This gives us the recurrence relation:
With the base case (since the loop condition is false), we compute:
Thus, the total number of times the printf statement is executed is 14.
Free practice · Your answers on this page are not saved.
