我应该始终明确关闭标准输出吗?

Should I always close stdout explicitly?

我正在尝试集成一个小型 Win32 C++ 程序,该程序从 stdin 读取并将解码结果(~128 kbytes)写入输出流。

我用

将整个输入读入缓冲区
while (std::cin.get(c)) { }

在我将整个输出写入标准输出之后。

当我从命令行 运行 应用程序时一切正常,例如 test.exe < input.bin > output.bin,但是这个小应用程序应该是 运行 来自 Python.

我希望应该使用 Python subprocess.communicate,文档说:

Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate.

所以 communicate() 将等到文件结束后再等待我的应用程序完成 - EOF 应该在我的应用程序退出时发生吗?或者我应该明确地执行 fclose(stderr) 和 fclose(stdout) 吗?

不要关闭标准输出

在一般情况下,这实际上是错误的,因为可以使用 atexit() 注册一个尝试写入标准输出的函数,如果关闭标准输出,这将中断。

当进程终止时,操作系统会自动关闭所有句柄。这包括标准输出,因此您无需手动关闭它。

(从技术上讲,C++ 运行时会 normally try to flush and close all C++ streams before the OS even has a chance to get involved, but the OS absolutely must close any handles which the runtime, for whatever reason,未命中。)

在特殊情况下,关闭标准流可能很有用(例如,在守护进程时),但应该非常小心。重定向到空设备或从空设备(Unix 上的 /dev/null,Windows 上的 nul)重定向通常是个好主意,这样期望与这些流交互的代码仍然可以工作。在 Unix 上,这是用 freopen(3); Windows has an equivalent function 完成的,但它是 POSIX API 的一部分,可能无法很好地与标准 Windows I/O.[=17= 一起使用]