我应该总是明确关闭标准输出吗? [英] Should I always close stdout explicitly?

查看:70
本文介绍了我应该总是明确关闭标准输出吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试集成一个小型 Win32 C++ 程序,该程序从标准输入读取并将解码结果(约 128 KB)写入输出流.

I am trying to integrate a small Win32 C++ program which reads from stdin and writes the decoded result (˜128 kbytes)to the output stream.

我用

while (std::cin.get(c)) { }

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

After I write entire output to the stdout.

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

Everything works fine when I run the application from command line eg test.exe < input.bin > output.bin, however this small app is supposed to be run from Python.

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

I expect that Python subprocess.communicate is supposed to be used, the docs say:

与进程交互:将数据发送到标准输入.从标准输出和读取数据stderr,直到到达文件尾.等待进程终止.

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) 吗?

So communicate() will wait until the end-of-file before waiting my app to finish - is EOF supposed to happen when my application exits? Or should I explicitly do fclose(stderr) and fclose(stdout)?

推荐答案

不要关闭标准输出

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

In the general case, it is actually wrong, since it is possible to register a function with atexit() which tries to write to stdout, and this will break if stdout is closed.

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

When the process terminates, all handles are closed by the operating system automatically. This includes stdout, so you are not responsible for closing it manually.

(从技术上讲,C++ 运行时将正常尝试刷新并关闭所有 C++在操作系统甚至有机会参与之前的流,但操作系统绝对必须关闭运行时的任何句柄,对于随便 原因,未命中.)

(Technically, the C++ runtime will 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, misses.)

在特殊情况下,关闭标准流可能很有用(例如,在进行守护进程时),但应非常小心地进行.重定向到或从空设备(Unix 上的 /dev/null ,Windows 上的 nul )通常是一个好主意,以便期望与这些流交互的代码仍然工作.在 Unix 上,这是通过 freopen(3) 完成的;Windows 具有等效功能,但它是 POSIX API 的一部分,并且可能不适用于标准 Windows I/O.

In specialized circumstances, it may be useful to close standard streams (for example, when daemonizing), but it should be done with great care. It's usually a good idea to redirect to or from the null device (/dev/null on Unix, nul on Windows) so that code expecting to interact with those streams will still work. On Unix, this is done with freopen(3); Windows has an equivalent function, but it's part of the POSIX API and may not work well with standard Windows I/O.

这篇关于我应该总是明确关闭标准输出吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆