It turns out that flush was not carefully studied during C programming.
Two days ago, the boss assigned me a question about whether the HTTP persistent connection is feasible, that is, the server continuously sends data to the HTTP client.
I use CGI programming. One of them is a while loop that keeps a certain character of printf. The plan is as follows:
While (1)
{
...
Printf ("C ");//
...
}
Since you do not want to print these C characters too quickly, modify the following:
Int COUNT = 0;
While (1)
{
...
Printf ("C ");//
Count ++
Sleep (1)
If (10 = count)]
{
... // Do something
}
...
}
After the program is compiled and run, it is found that it does not print a character in one second as designed. I haven't found any reason after searching for a long time. Just remove sleep (1.
But why?
It was found that printf was first written to the buffer when printing. If it was not printed to a certain extent, it was also said that printf was a row buffer.
For example:
# Include "stdio. H"
Int main (INT argc, char ** argv)
{
While (1)
{
Printf ("Hello World ");
Sleep (1 );
}
Return 0;
}
It's easy. The compilation is successful, and it doesn't take a second to print a "hello World" for you to run. You can replace the above Code with the following two methods:
First:
# Include "stdio. H"
Int main (INT argc, char ** argv)
{
While (1)
{
Printf ("Hello World ");
Fflush (stdout );
Sleep (1 );
}
Return 0;
}
Second:
# Include "stdio. H"
Int main (INT argc, char ** argv)
{
While (1)
{
Printf ("Hello World/N ");
Sleep (1 );
}
Return 0;
}
I checked some information and said:
1. Int fflush (File * stream );
The data in the buffer is forcibly written back to the file specified by the parameter stream.
2. stdout, stdin has a buffer, and stderr has no buffer.
Fflush () is used to send read or write data to stdout or stdin immediately.
I wrote it here today to remind myself that in the future, I will come up with a solution and remind csdn's friends.
Boatman 2010-8-27