如何控制的popen标准输入,标准输出,标准错误重定向? [英] how to control popen stdin, stdout, stderr redirection?

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

问题描述

我感到困惑的是如何的popen()重定向标准输入,输出和UNIX中的子进程的标准错误。上的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");

叉一个子进程,并执行与参数-c,在/ usr /斌/ foo的外壳,并重定向这个壳(这是重定向富的标准输入)的标准输入,标准输出为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,插座,接受等),以及父进程没有标准输出,它被分配下一个可用的文件号,这是1,依此类推。这也提供了从像fprintf中调用意外的结果(标准错误,...)。

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)只是一个库函数,它依赖于叉(2)管(2)做真正的工作。

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

管(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.

如果你想捕捉的标准错误太,这是可能的,但你需要的管道,和一个选择循环仲裁之间读取标准输出标准错误流。

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.

有有一个例子<一个href=\"http://jineshkj.word$p$pss.com/2006/12/22/how-to-capture-stdin-stdout-and-stderr-of-child-program/\">here为双管版本

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

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

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