setvbuf()-buf为NULL时的size参数 [英] setvbuf() - size parameter when buf is NULL
问题描述
当我运行以下代码时:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, char* argv)
{
int i=0;
setvbuf(stdout, NULL, _IOLBF,0);
while (1)
printf("%d ",i++);
return 0;
}
无论我为setvbuf()定义的 size 大小,它均以1024个字符为单位打印. 问题是在这种情况下 size 是否会有所影响,而1024个字符的定义从何而来.
it prints in chunks of 1024 chars, no matter the size I define for setvbuf(). The question is is if size affects somehow in this case and where is the definition for 1024 chars is coming from.
推荐答案
我不知道您是如何识别1024
的,但可能是BUFSIZ
. BUFSIZ
在stdio.h
中定义.
I don't know how you identified 1024
but it's probably BUFSIZ
. BUFSIZ
is defined in stdio.h
.
如果buf为NULL,则stdio库 自动为分配一个缓冲区 与流一起使用(除非我们选择 无缓冲的I/O).
If buf is NULL, then the stdio library automatically allocates a buffer for use with stream (unless we select unbuffered I/O).
编辑
这是glibc
说的话:
宏:int BUFSIZ 该宏的值是一个整数常量表达式,它是 很好用于size参数 setvbuf.此值保证 至少为256 .
Macro: int BUFSIZ The value of this macro is an integer constant expression that is good to use for the size argument to setvbuf. This value is guaranteed to be at least 256.
在每个系统上选择BUFSIZ的值,以便进行流I/O 高效的.所以使用是一个好主意 BUFSIZ作为缓冲区的大小,当 你叫setvbuf.
The value of BUFSIZ is chosen on each system so as to make stream I/O efficient. So it is a good idea to use BUFSIZ as the size for the buffer when you call setvbuf.
编辑2
@larsmans是正确的.我查看了setvbuf
的实现方式,并在请求行缓冲并显示NULL buf时忽略了调用.现在,stdout
不是普通文件,它已附加到终端.因此,转到 pixelbeat
@larsmans is right. I looked at how setvbuf
is implemented and it ignores a call when asking for line buffering and presenting a NULL buf. Now, stdout
is no ordinary file, it's attached to a terminal. So, heading over to pixelbeat
- 缓冲区大小仅直接影响缓冲模式
- 默认大小(如内核)基于页面大小(在4096字节上) 我的系统)
- 如果stdin/stdout连接到终端,则默认大小= 1024;
其他大小= 4096
- Buffer size only directly affects buffered mode
- The default size like the kernel is based on the page size (4096 bytes on my system)
- if stdin/stdout are connected to a terminal then default size = 1024;
else size = 4096
这篇关于setvbuf()-buf为NULL时的size参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!