Consider the following program snippet. Assume that the program compiles and runs successfully. Further, assume that the fork() system call is always successful in creating a process.
int main () {
int i;
for (i = 0; i < 3; i++) {
if (fork() == 0) {
continue;
}
break;
}
printf("Hello!");
return 0;
}The total number of times that the printf statement gets executed is . (answer in integer)
View worked solution
Answer: 4 : 4
Let us trace the execution of the program step-by-step. Let the initial process be .
- Iteration :
calls
fork(), creating a child process .- For the parent ,
fork()returns non-zero. It executes thebreakstatement, exits the loop, and prints "Hello!". - For the child ,
fork()returns . It executescontinueand proceeds to the next iteration ().
- For the parent ,
- Iteration :
calls
fork(), creating a child process .- For the parent ,
fork()returns non-zero. It executesbreak, exits the loop, and prints "Hello!". - For the child ,
fork()returns . It executescontinueand proceeds to the next iteration ().
- For the parent ,
- Iteration :
calls
fork(), creating a child process .- For the parent ,
fork()returns non-zero. It executesbreak, exits the loop, and prints "Hello!". - For the child ,
fork()returns . It executescontinue. The loop variable is incremented to , making the loop condition false. exits the loop and prints "Hello!".
- For the parent ,
Thus, exactly processes ( and ) exit the loop and execute the printf statement once each.
Therefore, the total number of times the printf statement gets executed is 4.
Free practice · Your answers on this page are not saved.
