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)Correct : 4
To determine how many times "Hello!" is printed, we need to trace the creation of processes using the fork() system call and understand how the continue and break statements affect the loop''s control flow.
Understanding the Code Mechanics
- fork() creates a new child process. It returns 0 to the child process, and a non-zero process ID to the parent process.
- if (fork() == 0) means only the child process evaluates the condition as true and enters the if block to execute continue;.
- The continue statement skips the rest of the current loop body and immediately moves to the next iteration (i increments).
- The parent process evaluates the if condition as false, bypasses the block, hits break;, immediately exits the loop entirely, and goes straight to the printf statement.
Tracing the Loop Execution
Let''s call our initial main process P0.
Iteration i = 0:
- P0 executes fork(), creating child P1.
- P0 (Parent): Hits break, exits the loop. (It is now ready to print "Hello!").
- P1 (Child): Hits continue, loops back. i becomes 1.
Iteration i = 1 (Only P1 is running this):
- P1 executes fork(), creating child P2.
- P1 (Parent): Hits break, exits the loop. (It is now ready to print "Hello!").
- P2 (Child): Hits continue, loops back. i becomes 2.
Iteration i = 2 (Only P2 is running this):
- P2 executes fork(), creating child P3.
- P2 (Parent): Hits break, exits the loop. (It is now ready to print "Hello!").
- P3 (Child): Hits continue, loops back. i becomes 3.
Loop Termination (i = 3):
- For P3, the condition i < 3 is now false. The loop terminates. (It is now ready to print "Hello!").
Conclusion
There are 4 distinct processes in total (P0, P1, P2, P3) that exit the loop and reach the printf("Hello!"); statement.
Therefore, the statement is executed exactly 4 times.
Correct Answer: 4
Similar Questions
Total Unique Visitors