为什么使用fprintf时标准输出不会打印?

16

我有这样的一段代码:

#include <stdio.h>
#include <unistd.h>
int main()
{
        while(1)
        {
                fprintf(stdout,"hello-out");
                fprintf(stderr,"hello-err");
                sleep(1);
        }
        return 0;
}
输出为 hello-err hello-err hello-err hello-err hello-err hello-err,每隔1秒钟输出一次。我想知道为什么没有打印出hello-out

2
很好,清晰的问题。+111111! - Linuxios
2个回答

15

通常情况下,stdout 是按行缓冲的,并且在程序中没有输出新行字符时需要使用 fflush 来清空 stdout

            fprintf(stdout,"hello-out");
            fflush(stdout);

stderr 默认情况下不是完全缓存的,因此您不需要使用 fflush


2

默认情况下,stdout是按行缓冲的,这意味着缓冲区将在每个行末('\n')刷新。

stderr是无缓冲的,因此每个字符都会自动发送,无需刷新。

您可以通过在stdout输出末尾放置\n来确认这一点。这样,两个行将以1秒间隔打印。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接