C:如何将 stderr 从系统命令重定向到 stdout 或文件?
shell 命令 $ avrdude -c usbtiny
将文本输出到 stderr。我无法使用 head-less-more 等命令来读取它,因为它不是标准输出。我想要将文本输出到标准输出或文件。我怎样才能在C中做到这一点?我试图通过我的最后一个问题解决问题,但仍未解决。
The shell command $ avrdude -c usbtiny
outputs text to stderr. I cannot read it with commmands such as head-less-more cos it is not stdout. I want the text to stdout or to a file. How can I do it in C? I have tried to solve the problem by my last question but still unsolved.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
通过阅读
man fork
、man exec
了解如何启动子进程来获取其 stderr Start。查看man 7 signal
、man sigaction
和man wait
了解如何获取子进程。最后是
man dup2
。未经测试的代码为例:
使用 dup2(),我们将子级的 stderr(即 fd 2)替换为管道的写入端。 pipeline() 在 fork() 之前调用。在 fork 之后,我们还必须关闭管道的所有悬挂端,以便父进程中的读取实际上会收到 EOF。
可能有一个使用 stdio 的更简单的解决方案,但我不知道。由于 popen() 通过 shell 运行命令,因此可能可以告诉它将 stderr 重定向到 stdout(并将 stdout 发送到 /dev/null)。从来没有尝试过。
还可以使用 mktemp() (
man 3 mktemp
) 创建临时文件名,为 system() 编写命令以将命令的 stderr 重定向到临时文件,并在 system() 返回后读取临时文件。Start by reading
man fork
,man exec
on how to start a child process. Look intoman 7 signal
,man sigaction
andman wait
for how to reap the child.Finally, the
man dup2
.Untested code to exemplify:
Using dup2() we replace stderr (which is fd 2) of the child with a writing end of a pipe. pipe() is called before fork(). After fork we also have to close all hanging ends of the pipe so that the reading in parent process would actually receive EOF.
Probably there is a simpler solution using stdio, but I'm not aware of it. Since popen() runs the command via shell, probably one can tell it to redirect stderr to stdout (and send stdout to /dev/null). Never tried that.
One can also use mktemp() (
man 3 mktemp
) to create a temp file name, compose command for system() to redirect stderr of the command to the temp file and after system() returns read the temp file.我还没有在 OpenBSD 中尝试过类似的操作,但至少在一些类似 *nix 的系统中,您可以使用 dup2 来完成此操作。
I've not tried something like this in OpenBSD, but in at least a few *nix-like systems, you can do this using
dup2
.正常的方式是这样的:
这将通常进入 stderr 的内容引导到 stdout 。如果您希望将其定向到文件,您可以执行以下操作:
The normal way would be something like:
This directs what would normally go to stderr to go to stdout instead. If you'd prefer to direct it to a file, you could do something like:
下面使用 POSIX 函数将标准输出文件号复制到标准错误文件号。将 stderr 复制到 stdout 的 POSIX 页面中给出了
dup2
作为该函数的示例用法。The following uses the POSIX function to duplicate the standard output file number into the standard error file number. Duplicating stderr to stdout is given in the POSIX page for
dup2
as an example usage of the function.