c – 为什么是stdout缓冲?

我正在尝试学习libuv api并写下面的测试:
#include <stdio.h>
#include <stdlib.h>
#include <uv.h>

void timer_cb(uv_timer_t* timer) {
    int* i = timer->data;
    --*i;
    if(*i == 0) {
       uv_timer_stop(timer);
    }
    printf("timer %d\n",*i);
    //fflush(stdout);
}

int main() {
    uv_loop_t* loop = uv_default_loop();
    uv_timer_t* timer = malloc(sizeof(uv_timer_t));
    uv_timer_init(loop,timer);
    int i = 5;
    timer->data = &i;
    uv_timer_start(timer,timer_cb,1000,2000);

    uv_run(loop,UV_RUN_DEFAULT);

    printf("Now quitting.\n");
    uv_close(timer,0);
    uv_loop_close(loop);

    return 0;
}

运行时,程序完成运行之前不显示任何输出,然后立即显示所有输出.如果我取消注释fflush行它按预期工作,每2秒写一次.

有人可以向我解释一下吗?为什么stdout在换行之后不会刷新,如here和其他地方所述?为什么需要手工冲洗?

解决方法

流缓冲是实现定义的.

每7.21.3文件,C Standard的第3段:

When a stream is
unbuffered,characters are intended to appear from the source or at the destination as soon as possible. Otherwise characters
may be accumulated and transmitted to or from the host
environment as a block. When a stream is
fully buffered,characters are intended to be transmitted to or from the host environment as a block when a buffer is filled. When a
stream is
line buffered,characters are intended to be transmitted to or from the host environment as a block when a new-line
character is encountered. Furthermore,characters are intended to be
transmitted as a block to the host environment when a buffer is
filled,when input is requested on an unbuffered stream,or when
input is requested on a line buffered stream that requires
the transmission of characters from the host
environment. Support for these characteristics is
implementation-defined
,and may be affected via the setbuf and
setvbuf functions.

缓冲的类型取决于您的实现,您的实现显然在您的示例中不是线缓冲.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...