繁体   English   中英

有人可以解释stdio缓冲是如何工作的吗?

[英]Can someone please explain how stdio buffering works?

我不明白缓冲区在做什么以及它是如何使用的。 (另外,如果你能解释缓冲区通常做什么)特别是,为什么在这个例子中我需要 fflush ?

int main(int argc, char **argv)
{
    int pid, status;
    int newfd;  /* new file descriptor */

    if (argc != 2) {
        fprintf(stderr, "usage: %s output_file\n", argv[0]);
        exit(1);
    }
    if ((newfd = open(argv[1], O_CREAT|O_TRUNC|O_WRONLY, 0644)) < 0) {
        perror(argv[1]);    /* open failed */
        exit(1);
    }
    printf("This goes to the standard output.\n");
    printf("Now the standard output will go to \"%s\".\n", argv[1]);
    fflush(stdout);

    /* this new file will become the standard output */
    /* standard output is file descriptor 1, so we use dup2 to */
    /* to copy the new file descriptor onto file descriptor 1 */
    /* dup2 will close the current standard output */

    dup2(newfd, 1); 

    printf("This goes to the standard output too.\n");
    exit(0);
}

在 UNIX 系统中,标准输出缓冲恰好可以提高 I/O 性能。 每次都做 I/O 会非常昂贵。

如果你真的不想缓冲有一些选择:

  1. 禁用缓冲调用setvbuf http://www.cplusplus.com/reference/cstdio/setvbuf/

  2. 当你想刷新缓冲区时调用flush

  3. 输出到 stderr(默认情况下是无缓冲的)

在这里你有更多的细节: http : //www.turnkeylinux.org/blog/unix-buffering

I/O 是一项开销很大的操作,因此为了减少 I/O 操作的次数,系统会将信息存储在临时内存位置,并将 I/O 操作延迟到有大量数据的时刻。

通过这种方式,您的 I/O 操作数量要少得多,这意味着应用程序速度更快。

danielfraca 回答了大部分问题,但还有另一部分:流上的默认缓冲是什么?

当且仅当它引用终端时,默认情况下输出流是行缓冲的。 否则它是全缓冲的。 另请注意,如果写入的字节数超过BUFSIZ (通常为 512 和 8192 之间的 2 的幂),则两种缓冲都将自动刷新。

所以这个程序:

#include <stdio.h>
#include <unistd.h>

int main()
{
    puts("Hello");
    fork();
    puts("World");
}

产生这个输出:

% ./fork 
Hello
World
World
% ./fork | cat
Hello
World
Hello
World

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM