Sleep and output flush
I saw the snippet below somewhere online. The following program doesnt print "hello-out"开发者_StackOverflow中文版. The reason I feel is because before it is actually flushed to the console from the buffer,
#include <stdio.h>
#include <unistd.h>
int main()
{
while(1)
{
fprintf(stdout,"hello-out");
fprintf(stderr,"hello-err");
sleep(1);
}
return 0;
}
Is my reason correct? If not what is the correct reason?
You should put \n
at the end of the string to have it flushed, or use fflush
to force it out.
The reason the following fix is because I do know that stdout is line-buffered by default, whereas stderr is not.
#include <stdio.h>
#include <unistd.h>
int main()
{
while(1)
{
fprintf(stdout,"hello-out");
fflush(stdout);
// sleep(1);
fprintf(stderr,"hello-err");
sleep(1);
}
return 0;
}
Update another way to 'fix' it without changing the source code is by using e.g. stdbuf
:
stdbuf -o 0 ./test
which switches standard output to unbuffer mode as well. Interestingly, if you specify
stdbuf -e L ./test
to make stderr linebuffered as well, no output will appear at all (until the first lineend gets printed)
精彩评论