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+⬑ * 默认成员函数 原来C++类中,有6个默认成员函数: 构造函数 析构函数 拷贝...
#pragma once // 1. 设计一个不能被拷贝的类/* 解析:拷贝只会放生在两个场景中:拷贝构造函数以及赋值运...
C类型转换 C语言:显式和隐式类型转换 隐式类型转化:编译器在编译阶段自动进行,能转就转,不能转就编译...
//异常的概念/*抛出异常后必须要捕获,否则终止程序(到最外层后会交给main管理,main的行为就是终止) try...
#pragma once /*Smart pointer 智能指针;灵巧指针 智能指针三大件//1.RAII//2.像指针一样使用//3.拷贝问...
目录&lt;future&gt;future模板类成员函数:promise类promise的使用例程:packaged_task模板类例程...