I am trying the following C code:
int main()
{
printf(\"text1\\n\");
fork();
printf(\"text2\\n\");
return 0;
}
I was expect
fork clones the current process. The new process will "start" at the fork call, not at the start of main as you seem to expect. Thus when you print the first time there is 1 process, then when you fork there are two.
Since you are forking after printing "text1", it is only printed once.
In the second example the duplicated output is due to output buffering - printf doesn't actually output anything to the screen until it is flushed or it hits a newline ('\n').
Consequently the first call to printf actually just wrote data to a buffer somewhere, the data was then copied into the second process' address space, and then the second call to printf would have flushed the buffer, complete with "text1" in both buffers.