Question: How many "-" statements are output by the following program?
[Cpp]
# Include <stdio. h>
# Include <sys/types. h>
# Include <unistd. h>
Int main (void)
{
Int I;
For (I = 0; I <2; I ++ ){
Fork ();
Printf ("-");
}
Return 0;
}
Generally, if you are familiar with the fork mechanism, you will think that the output is 6 '-'.
For basic knowledge, see the previous question.
>>> When the program is started, bash generates a process P1 to execute the program,
>>> After P1 enters the program, when I = 0, fork () generates a sub-process P2 and outputs a '-' by itself '-'.
>>> P2 inherits environment P1, such as environment variables and PCs. P2 outputs a '-' at the beginning '-'. at the same time, I = 1, will continue to execute the for loop --- P2 first fork () out of a sub-process P3, and then output '-'.
>>> A child process whose P3 process is P2 replicates the command, variable value, program call stack, environment variable, and buffer of its parent process P2. It outputs '-'
Here, P3 inherits the P2 buffer, and one of them is '-'. Therefore, P3 outputs two '-'.
>>> After P1 enters the program, when I = 1, fork () generates another child process P4 and outputs a '-' at the same time '-'.
>>> P4 also outputs '-'.
Because a child process whose P4 is P1 inherits the buffer zone of P1, there is a '-', so P4 outputs two '-'.
We normally think that the above analysis should generate 6 '-'.
But why are there eight? See the analysis on the red part.
This is because the printf ("-"); statement has buffer, so for the above program, printf ("-"); Put "-" in the cache, when fork, the cache is copied to the sub-process space. Therefore, if there are two more, eight instead of six.
If you change printf ("-")
[Cpp]
Printf ("-\ n ");
Or call fflush to clear the cache.
[Cpp]
Printf ("-");
Fflush (stdout );
You can always ensure that 6 '-' are output '-'