有人可以解释一下stdio缓冲的工作原理吗? [英] Can someone please explain how stdio buffering works?

查看:53
本文介绍了有人可以解释一下stdio缓冲的工作原理吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道缓冲区在做什么以及如何使用.(此外,如果您可以解释缓冲区的正常功能)特别是为什么在此示例中需要使用fflush?

I don't understand what the buffer is doing and how it's used. (Also, if you can explain what a buffer normally does) In particular, why do I need fflush in this example?

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系统中,stdout缓冲可以提高I/O性能.每次执行I/O都将非常昂贵.

In a UNIX system the stdout buffering happens to improve I/O performance. It would be very expensive to do I/O every time.

如果您真的不想缓冲,则有一些选择:

If you really don't want to buffer there's some options:

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

要刷新缓冲区时调用flush

Call flush when you want to flush the buffer

输出到stderr(默认情况下为无缓冲)

Output to stderr (that's unbuffered by default)

这里有更多详细信息: http://www.turnkeylinux.org/blog/unix-缓冲

Here you've more details: http://www.turnkeylinux.org/blog/unix-buffering

I/O是一项昂贵的操作,因此,为了减少I/O操作的数量,系统会将信息存储在临时存储位置中,并将I/O操作延迟到其具有大量数据的时刻

I/O is an expensive operation, so to reduce the number of I/O operations the system store the information in a temporary memory location, and delay the I/O operation to a moment when it has a good amount of data.

这样,您的I/O操作数量少得多,这意味着应用程序速度更快.

This way you've a much smaller number of I/O operations, what means, a faster application.

这篇关于有人可以解释一下stdio缓冲的工作原理吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆