如何控制 popen stdin、stdout、stderr 重定向? [英] how to control popen stdin, stdout, stderr redirection?

查看:34
本文介绍了如何控制 popen stdin、stdout、stderr 重定向?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 popen() 如何在 unix 中重定向子进程的 stdin、stdout 和 stderr 感到困惑.popen() 上的手册页在这方面不是很清楚.电话

I am confused about how popen() redirects stdin, stdout and stderr of the child process in unix. The man page on popen() is not very clear in this regard. The call

FILE *p = popen("/usr/bin/foo", "w");

fork 一个子进程并执行一个带有参数-c"、/usr/bin/foo"的shell,并将这个shell的stdin(它被重定向到foo的stdin),stdout重定向到p.但是标准错误会发生什么?其背后的一般原则是什么?

forks a child process and executes a shell with arguments "-c", "/usr/bin/foo", and redirects stdin of this shell (which is redirected stdin of foo), stdout to p. But what happens with stderr? What is the general principle behind it?

我注意到,如果我在 foo 中打开一个文件(使用 fopen、socket、accept 等),并且父进程没有标准输出,它会被分配下一个可用的文件编号,即 1,依此类推.这会从 fprintf(stderr, ...) 之类的调用中产生意想不到的结果.

I noticed that, if I open a file in foo (using fopen, socket, accept etc.), and the parent process has no stdout, it gets assigned the next available file number, which is 1 and so on. This delivers unexpected results from calls like fprintf(stderr, ...).

可以通过写来避免

FILE *p = popen("/usr/bin/foo 2>/dev/null", "w");

在父程序中,但它们有更好的方法吗?

in the parent program, but are their better ways?

推荐答案

popen(3) 只是一个库函数,它依赖于 fork(2)pipe(2) 来做真正的工作.

popen(3) is just a library function, which relies on fork(2) and pipe(2) to do the real work.

然而pipe(2) 只能创建单向管道.要发送子进程输入并捕获输出,您需要打开两个管道.

However pipe(2) can only create unidirectional pipes. To send the child process input, and also capture the output, you need to open two pipes.

如果您也想捕获 stderr,这是可能的,但是您需要 三个 管道和一个 select 循环来在 stdoutstderr 流之间仲裁读取.

If you want to capture the stderr too, that's possible, but then you'll need three pipes, and a select loop to arbitrate reads between the stdout and stderr streams.

有一个例子 此处 用于两管道版本.

There's an example here for the two-pipe version.

这篇关于如何控制 popen stdin、stdout、stderr 重定向?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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