我正在编写一个用于运行程序的实用程序,我需要从程序中捕获无缓冲的标准输出和标准错误。我需要:
- 捕获 stdout 和 stderr 以分隔文件。
- 输出不需要缓冲(或行缓冲)。
- 不修改正在运行的程序的源代码。
问题是,当管道输出到文件时,stdout 流变为 block 缓冲而不是行缓冲。如果程序崩溃,输出永远不会被刷新,并且是空白的。所以我需要在没有缓冲(或行缓冲)的情况下捕获标准输出。
我认为这可以通过 pty 来完成,但我很难找到完全符合我要求的示例(大多数忽略 stderr)。事实上,我不确定我是否在 C 中找到了任何 pty 示例;大多数使用更高级别的接口(interface),如 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
我的代码可作为存储库使用:
最佳答案
参见man 7 pty
特别是:
Unix 98 pseudo-terminals
An unused Unix 98 pseudo-terminal master is opened by calling
posix_openpt(3)
. (This function opens the master clone device,/dev/ptmx
; seepts(4)
.) After performing any program-specific initializations, changing the ownership and permissions of the slave device usinggrantpt(3)
, and unlocking the slave usingunlockpt(3)
), the corresponding slave device can be opened by passing the name returned byptsname(3)
in a call toopen(2)
.
现在您知道了此类代码需要调用的库函数的名称,您可以做两件有用的事情:
- 查看他们的手册页
- 谷歌示例代码。既然您知道要在搜索引擎中使用哪些关键字,我想您会更幸运地找到示例。
关于c - 如何在不修改程序的情况下从 stdout 捕获无缓冲的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1551436/