I am learning the fork function in C, and was studying for the past exams and came across one question which is quite interesting.
See the code below:
int main(void) {
printf("Hello ");
fork();
printf("Hello ");
fork();
printf("Hello \n");
pause();
return 0;
}
The result output is
Hello Hello Hello
Hello Hello Hello
Hello Hello Hello
Hello Hello Hello
If I alter my code to
fork();
fork();
printf("Hello ");
printf("Hello ");
printf("Hello \n");
The output result is still the same. Why the location of the fork function has no effect on the output itself. Does fork waits for all the printf() to finish before executing? That should explain the output, because the first time printf() will print out the first line of Hello, then it will be forked and 1 more lines of Hello will be printed. Then the 2nd fork will fork the previous 2 lines and produce the 2 more line of Hello.
However, the question alters the code just by a bit and the whole output changes dramatically.
printf("Hello \n");
fork();
printf("Hello ");
fork();
printf("Hello \n");
This results in the output being
Hello
Hello Hello
Hello Hello
Hello Hello
Hello Hello
I do not understand why just adding a '\n' will result in 5 lines of output instead of 4. This time, if I change the location of the fork function to the top like before, the output changes too. It seems that the fork function had no effect on the first line of printf this time. Can someone explain to me how exactly does fork function outputs stuff?