Another interview question related to fork

Source: Internet
Author: User

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 '-'

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.