【问题标题】:Standard error and standard output标准错误和标准输出
【发布时间】:2014-04-16 17:04:35
【问题描述】:

假设我有这种情况: 我将某些程序的标准错误重定向到文件 output.err 并将标准输出重定向到文件 output.out。当程序运行但在允许正常完成之前被杀死时,我注意到 output.err 文件包含预期的输出,但是即使我保证执行了适当的 printf 语句,该 output.out 也是空的。 这是为什么呢?

【问题讨论】:

  • stdout 是缓冲的,而 stderr 不是,所以 stderr 在写入时会命中文件,而不是稍后。

标签: c error-handling


【解决方案1】:

这是因为 STDERR 从不缓冲。这意味着无论如何数据都会立即写入。要刷新 STDOUT 中的缓冲数据,您可以使用此函数:

some_write_operation_on_stdout();
fflush(stdout);

此调用导致数据从缓冲区中刷新并写入,就好像它没有缓冲一样。要永久禁用 STDOUT 的缓冲,您只需调用一次:

setbuf(stdout, NULL);

请参阅Why does printf not flush after the call unless a newline is in the format string? 了解更多信息。

【讨论】:

    【解决方案2】:

    这可能是因为程序使用库来写入包含缓冲区的输出(C 的 stdout 文件流通常就是这种情况),并且在刷新缓冲区之前输出实际上并未写入设备(当你杀死程序时不会发生这种情况)。相比之下,C 的stderr 是无缓冲的。 (缓冲可以用setbuf()控制。)

    【讨论】: