我正在运行一个启动进程的程序,然后该进程写入我的程序使用的标准输出。问题是,我需要的输出大约是 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, thebuf
argument should point to a buffer at leastsize
bytes long; this buffer will be used instead of the current buffer. If the argumentbuf
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/