为什么使用fprintf时打印到stdout不会发生?

ins*_*ane 16 c printf stdout stderr

我有这个代码:

#include <stdio.h>
#include <unistd.h>
int main()
{
        while(1)
        {
                fprintf(stdout,"hello-out");
                fprintf(stderr,"hello-err");
                sleep(1);
        }
        return 0;
}
Run Code Online (Sandbox Code Playgroud)

输出hello-err hello-err hello-err hello-err hello-err hello-err 间隔为1秒.我想知道为什么hello-out永远不会被打印出来.

oua*_*uah 15

您需要,fflush stdout因为通常stdout是行缓冲,并且您不在程序中发出换行符.

            fprintf(stdout,"hello-out");
            fflush(stdout);
Run Code Online (Sandbox Code Playgroud)

stderr默认情况下没有完全缓冲,因此您不需要fflush它.