16

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.

4

2 回答 2

15

You need to fflush stdout because usually stdout is line buffered and you don't issue a new line character in your program.

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

stderr is not fully buffered by default so you don't need to fflush it.

于 2012-07-03T16:02:26.957 回答
2

stdout 默认情况下是行缓冲的,这意味着缓冲区将在每个行尾 ( '\n') 处刷新。stderr 是无缓冲的,因此每个字符都会自动发送而无需刷新。

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

于 2012-07-03T16:07:23.607 回答