setvbuf() - 当 buf 为 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;
}
它会以 1024 个字符的块形式打印,无论我为 setvbuf() 定义的大小。 问题是在这种情况下 size 是否会产生某种影响,以及 1024 个字符的定义来自哪里。
It seems that when I run the following code:
#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;
}
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不知道您是如何识别
1024
的,但它可能是BUFSIZ
。BUFSIZ
在stdio.h
中定义。编辑
这是
glibc
所说的:编辑2
@larsmans 是对的。我研究了 setvbuf 的实现方式,它在请求行缓冲并呈现 NULL buf 时忽略调用。现在,
stdout
不是普通文件,它附加到终端。因此,前往 pixelbeatI don't know how you identified
1024
but it's probablyBUFSIZ
.BUFSIZ
is defined instdio.h
.EDIT
Here's something
glibc
says:EDIT 2
@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根据C标准(草案),
所以,假设你测量正确,当
buf
为 null 时,Glibc 似乎可以自由地做它想做的事,并且它给你一个 1kB 的缓冲区。由于您从不写入换行符,因此行缓冲没有任何效果,并且行为类似于完全缓冲。According to the (draft) C standard,
So, assuming you measured correctly, it seems like Glibc is free to do as it pleases when
buf
is null, and it gives you a 1kB buffer. Since you never write a newline, line buffering has no effect and the behavior is similar to full buffering.大小对于 NULL buf 指针可能没有太大影响。
但是,您仍然使用
_IOLBF
请求缓冲输出,请尝试使用_IONBF
。http://en.wikipedia.org/wiki/Setvbuf
The size probably doesn't have much effect for a NULL buf pointer.
However, you are still requesting buffered output with
_IOLBF
Try_IONBF
instead.http://en.wikipedia.org/wiki/Setvbuf