In the past few days, I have watched Linux Application Programming and tested the fork function. Doesn't it mean that the sub-process will start running from the fork statement? Why is the previous printf content still output. I found it online. This is probably the case:
----------------------------
Main ()
{
Int;
Int pid;
Printf ("AAAAAAAA"); // Why is print
Twice
Pid = fork ();
If (pid = 0 ){
Printf ("OK ");}
Else if (pid>; 0 ){
Printf ("is OK \ n ");
}
Printf ("BBBBBBB ");
}
-----------------------------
If you replace printf ("AAAAAA") with printf ("AAAAAA \ n"), it is printed only once.
The main difference is that there is a \ n carriage return symbol.
This is related to the buffer mechanism of Printf. When printf contains some content, the operating system only places the content
The stdout Buffer Queue is in, and it is not actually written to the screen.
However, as long as \ n is displayed, stdout will be refreshed immediately, so it can be printed immediately.
After printf ("AAAAAA") is run, AAAAAA is only put in the buffer, and then in the fork
The AAAAAA quilt process inherits
Therefore, AAAAAA is also available in the stdout buffer.
So what you finally see is that AAAAAA was printf twice !!!!
After running printf ("AAAAAA \ n"), AAAAAA is immediately printed to the screen and then fork to the sub-process.
There will be no AAAAAA content in the stdout buffer.
The result you see is that AAAAAA is printf once !!!!