标准输出引起的重定向文件失败问题

由于输出很少,程序又不是正常结束(通过ctrl+c结束), 导致标准输出重定向到文件的内容为空

原因在于标准输出的缓冲模式

标准输出(stdout)的缓冲原理
缓冲类型分为三种:

  • 无缓冲
  • 行缓冲
  • 全缓冲

stderr默认缓冲就是无缓冲。而stdout的缓冲类型与输出介质有关:

屏幕或者终端:行缓冲
重定向文件、管道:全缓冲

为什么和输出介质有关,这很可能是shell重定向时候dup2的设置

解决方法一
显示调用fflush
这种方法的缺点有两个:效率、使用不方便。 (因为你可能需要重新设置信号处理函数来处理ctrl+c, 或者kill -9 这种情况根本无法解决)

解决方法二
c函数setvbuf
https://www.runoob.com/cprogramming/c-function-setvbuf.html

int setvbuf(FILE *stream, char *buf, int mode, size_t size);

setvbuf(stdout, NULL, _IOLBF, 0); //设置stdout的缓冲类型为行缓冲,

明确指定缓冲类型之后重定向就会使用该缓冲类型

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 cur rent 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. The setvbuf() function may be used only after opening a stream and before any other operations have been performed on it

注意这里setvbuf如果buf参数为NULL,则使用默认缓冲

另外行缓冲的语义是当遇到回车或者buffer满了之后真正输出到介质

全缓冲的语义就是buffer满了输出到介质

无缓冲就是直接输出到介质

发布了113 篇原创文章 · 获赞 22 · 访问量 9万+

猜你喜欢

转载自blog.csdn.net/woai110120130/article/details/102639191
今日推荐