Fork () is a very good example

Source: Internet
Author: User

# Include int main (void) {int P1; putchar ('x'); While (p1 = fork () =-1); If (p1 = 0) printf ("B"); else printf ("A"); printf ("Y ");}

The result is not xxbyay, but xbyxay. Why ..

 

Because the standard output is line buffered
The real branch of the program starts with the code after fork, and the first X is actually in the buffer (at this time there is no sub-process parent process concept ), when fork is used, the child process also copies a parent
The buffer of the process, so the sub-process will get X. Xby must be connected, because the default output is line.
Buffered, there is no output in case of carriage return. The buffer is cleared only when the process exits. Similarly, xay must be together.
The sequence of xay and xby is uncertain.

If you perform fflush first, there will be less X.
[Code]
# Include <stdio. h>
# Include <stdlib. h>
# Include <unistd. h>
Int main (void)
{
Int P1;

Putchar ('x ');
Fflush (stdout );
// Setbuf (stdout, null );
While (p1 = fork () =-1 );
If (p1 = 0)
Printf ("B ");
Else
Printf ("");
Printf ("Y ");
Return 0;
}
[/Code]
The result is
Xbyay

In other words, because stdout is line buffered by default, by must be connected together (only flush when the sub-process exits ), the same is true for ay. As for AY, the order of by is not necessarily

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.