c - 增加标准输出缓冲区大小

标签 c linux buffer

我正在运行一个启动进程的程序,然后该进程写入我的程序使用的标准输出。问题是,我需要的输出大约是 42000 字节。标准输出缓冲区大小似乎是 8192,我不希望它在达到 42000 之前刷新。有没有办法设置它?

我试过这个:

setvbuf ( stdout , NULL , _IOFBF , 50000 ); // ie set it to 50000 bytes

关于子进程的代码,但它似乎根本不起作用。有人有什么想法吗?

最佳答案

您需要为 setvbuf() 提供一个缓冲区才能工作。

static char buf[50000]; /* buf must survive until stdout is closed */
setvbuf ( stdout , buf , _IOFBF , sizeof(buf) );

来自man page :

int setvbuf(FILE *stream, char *buf, int mode , size_t size);
...
Except for unbuffered files, the buf argument should point to a buffer at least size bytes long; this buffer will be used instead of the current buffer. If the argument buf is NULL, only the mode is affected; a new buffer will be allocated on the next read or write operation.

这是一个示例程序:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main (int argc, char *argv[]) {
    char msg[42000];
    char buf[50000];

    setvbuf(stdout, buf, _IOFBF, sizeof(buf));
    memset(msg, 'a', sizeof(msg));
    msg[sizeof(msg)-1] = '\0';
    puts(msg);
    exit(0);
}

在我的系统上,strace 输出显示单次写入 42000 字节。

关于c - 增加标准输出缓冲区大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18243201/

相关文章:

linux - 从 Linux 上的 Windows pgp 可执行自解压存档中提取文件

c++ - 如何为 Fedora 安装 g++?

c - 将偶数带到数组 : How to incorporate corner case elegantly? 前面的算法

c - 在全局范围内使用自动变量

c++ - 将整数转换为字符数组函数

iphone - 应用程序处于后台状态时 AVPlayer 处理缓冲区

node.js - 将原始图像转换为缓冲区

c - 简单的 C If 语句

linux - 通过 SSL 的 Wget 给出 : Unable to establish SSL connection

java - 0x0A 和 0x0D 的区别