如何在不修改程序的情况下从标准输出捕获无缓冲的输出?
我正在编写一个用于运行程序的实用程序,我需要从程序中捕获无缓冲的标准输出和标准错误。我需要:
- 捕获 stdout 和 stderr 以分隔文件。
- 输出不需要缓冲(或行缓冲)。
- 无需修改正在运行的程序的源代码。
问题是,当通过管道输出到文件时,标准输出流变成块缓冲而不是行缓冲。如果程序崩溃,输出永远不会被刷新,并且是空白的。所以我需要在没有缓冲(或使用行缓冲)的情况下捕获标准输出。
我认为这可以用 pty 来完成,但我很难找到任何完全符合我想要的示例(大多数忽略 stderr)。事实上,我不确定我是否在 C 语言中找到了任何 pty 示例;大多数使用更高级别的接口,例如 Python 的 pty 和 subprocess 模块。
任何人都可以提供帮助(使用代码片段或链接)吗?任何帮助将不胜感激。
编辑:我想我已经解决了。以下两个链接非常有帮助。
- http://publib.boulder.ibm.com/infocenter/zos/v1r10/index.jsp?topic=/com.ibm.zos.r10.bpxbd00/posixopenpt.htm
- http://www.gidforums.com/t-3369.html
我的代码可作为存储库使用:
I'm writing a utility for running programs, and I need to capture unbuffered stdout and stderr from the programs. I need to:
- Capture stdout and stderr to separate files.
- Output needs to not be buffered (or be line buffered).
- Without modifying the source of the program being run.
The problem is, when piping output to a file, the stdout stream becomes block buffered rather than line buffered. If the program crashes, the output never gets flushed, and is blank. So I need to capture stdout without buffering (or with line buffering).
I think this can be done with pty's but I'm having difficulty finding any examples that do exactly what I want (most ignore stderr). In fact, I'm not sure I've found any pty examples in C at all; most use a higher-level interface like Python's pty and subprocess modules.
Can anyone help (with code snippets or links)? Any help would be appreciated.
EDIT: I think I've solved it. The following two links were pretty helpful.
- http://publib.boulder.ibm.com/infocenter/zos/v1r10/index.jsp?topic=/com.ibm.zos.r10.bpxbd00/posixopenpt.htm
- http://www.gidforums.com/t-3369.html
My code is available as a repository:
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
请参阅
man 7 pty
特别是:
现在您知道了此类代码需要调用的库函数的名称,您可以做两件有用的事情:
see
man 7 pty
In particular:
And now that you know the names of the library functions such a code will need to call, you can do two useful things: