I have this code:
我有这段代码:
#include <stdio.h>
#include <unistd.h>
int main()
{
while(1)
{
fprintf(stdout,"hello-out");
fprintf(stderr,"hello-err");
sleep(1);
}
return 0;
}
The output is hello-err
hello-err
hello-err
hello-err
hello-err
hello-err
at 1 sec intervals. I want to know why hello-out never gets printed.
输出是hello-err hello-err hello- ur -err,每间隔1秒。我想知道为什么helloout永远不会被打印出来。
2 个解决方案
#1
15
You need to fflush
stdout
because usually stdout
is line buffered and you don't issue a new line character in your program.
您需要fflush stdout,因为通常stdout是行缓冲的,而且在程序中不会发出新的行字符。
fprintf(stdout,"hello-out");
fflush(stdout);
stderr
is not fully buffered by default so you don't need to fflush
it.
stderr在默认情况下没有完全缓冲,所以不需要填充它。
#2
2
stdout is line-buffered by default, meaning that the buffer will be flushed at every end-of-line ('\n
'). stderr is unbuffured, so every character is sent automatically without the need to flush.
默认情况下,stdout是行缓冲的,这意味着缓冲区将在每个行结束时刷新('\n')。stderr是无缓冲的,所以每个字符都是自动发送的,不需要刷新。
You can confirm this by placing a \n
at the end of the stdout output. That way both lines will be printed at 1 second intervals.
您可以在stdout输出的末尾放置一个\n来确认这一点。这样,两行每隔1秒打印一次。
#1
15
You need to fflush
stdout
because usually stdout
is line buffered and you don't issue a new line character in your program.
您需要fflush stdout,因为通常stdout是行缓冲的,而且在程序中不会发出新的行字符。
fprintf(stdout,"hello-out");
fflush(stdout);
stderr
is not fully buffered by default so you don't need to fflush
it.
stderr在默认情况下没有完全缓冲,所以不需要填充它。
#2
2
stdout is line-buffered by default, meaning that the buffer will be flushed at every end-of-line ('\n
'). stderr is unbuffured, so every character is sent automatically without the need to flush.
默认情况下,stdout是行缓冲的,这意味着缓冲区将在每个行结束时刷新('\n')。stderr是无缓冲的,所以每个字符都是自动发送的,不需要刷新。
You can confirm this by placing a \n
at the end of the stdout output. That way both lines will be printed at 1 second intervals.
您可以在stdout输出的末尾放置一个\n来确认这一点。这样,两行每隔1秒打印一次。