重定向输出遇到的缓冲问题
来源:互联网 发布:dnf淘宝辅助怎么样 编辑:程序博客网 时间:2024/04/29 23:53
一个项目中需要迭代计算,时间长,但是在重定向输出的时候所有标准输出不能及时输出,这就要求程序主函数正常运行完后才能正常输出到文件。
因为标准输出到终端时默认行缓冲或无缓冲,重定向到硬盘之后,就变成了全缓冲
1. Fully buffered means that I/O takes place only when the buffer is fully, the process explicitly calls fflush, or the process terminates by calling exit. A common size for the standard I/O buffer is 8192 bytes;
2. Line buffered means that I/O takes place when a newline is encountered, when the process calls fflush, or when the process terminates by calling exit.
3. Unbuffered means that I/O take place each time a standard I/O output function is called.
解决方法有 fflush , setvbuf , 和伪终端
1. 每次printf时都刷新缓存区强制输出,fflush(stdout)
2. setvbuf 更改缓冲类型,手动设置缓冲区大小,使之足够小。
int setvbuf( FILE *stream, char *buffer, intmode, size_tsize);
The setvbuf function allows the program to control both buffering and buffer size forstream.stream must refer to an open file that has not undergone an I/O operation since it was opened. The array pointed to bybuffer is used as the buffer, unless it isNULL, in which casesetvbuf uses an automatically allocated buffer of lengthsize/2 * 2 bytes.
The mode must be _IOFBF, _IOLBF, or _IONBF. If mode is _IOFBF or _IOLBF, then size is used as the size of the buffer. If mode is_IONBF, the stream is unbuffered andsize andbuffer are ignored. Values formode and their meanings are:
_IOFBF
Full buffering; that is, buffer is used as the buffer andsize is used as the size of the buffer. Ifbuffer isNULL, an automatically allocated buffersize bytes long is used.
_IOLBF
With MS-DOS, the same as _IOFBF.
_IONBF
No buffer is used, regardless of buffer or size.
对于 _IOFBF _IOLBF ,dos上并没有区别,第四个参数size指定了缓冲区的大小,并且,当第二个参数,一个字符串buffer没有指定的情况下,系统将自动分配一片内存,长度为 (unsigned int)(size/2) * 2 ,每次向缓冲区写size个,大于缓冲区大小后,自动输出。
测试:
x.cpp
#include <stdio.h>#include <windows.h>int main(int argc, char *argv[]){setvbuf(stdout, 0, _IOFBF, 10);printf("hello world\n");Sleep(10000000);return 0;}
cl x.cpp
x > re.txt
pause
运行后直接退出
输出 hello worl
将10改成14后没有输出
改成4后输出 hello wo
在这个项目中 setvbuf(stdout, 0, _IONBF, 0);
- 重定向输出遇到的缓冲问题
- 重定向输出遇到的缓冲问题 .
- Linux 输出流重定向缓冲设置
- nginx域名重定向遇到的问题
- 关于dup2重定向STDOUT_FILENO之后的文件缓冲问题
- Linux标准输出行缓冲以及重定向
- 今天遇到的关于重定向地址栏乱码的问题
- 昨天竟然遇到一个重定向的问题
- 页面跳转 重定向(工作中遇到的问题)
- Android使用HttpURLConnection编程遇到的302重定向问题
- 关于记录Snort的执行情况,输出信息重定向问题
- Linux 标准输出重定向 缺失的问题
- java的输出在命令行中的重定向问题
- 批处理文件的输出重定向
- Linux的输出重定向
- 输出流的重定向
- 重定向的输出不见了?
- python 调用smtplib输出重定向问题
- 使用jquery实现图片等比例缩放
- NSTimer 小结
- iOS开发记录(1)
- H3C 交换机中 SI与EI区别
- Flex4 ComboBox 输入中文
- 重定向输出遇到的缓冲问题
- win7系统下两台笔记本用一条网线共享上网的设置方法!一条网线,不用路由器,多台笔记本电脑共享上网!
- DMZ network
- 算法之直接插入排序降序,升序
- 05 - 基本控件:Clock时钟(AnalogClock、DigitalClock)、Chronometer计时器
- 用css3和jquery实现的渐变的动态进度条
- cas+acegi中app-config-acegi-security.xml的配置
- 学习GD库操作步骤 2012-12-11 10:50am
- java字符串转换