Question about Printing printf twice before fork ()

Source: Internet
Author: User

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

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.