如何捕获execvp的输出 [英] How to capture output of execvp
问题描述
我正在开发一个程序,该程序使用execvp执行程序.它需要捕获子过程的结果并在主过程中对其进行解析.似乎有一种方法可以使用命名管道和duping.我正在尝试寻找一个很好的例子,但是到目前为止还没有运气.如果有人对此有任何指示,链接和/或建议,我将不胜感激.
I'm developing a program which executes a program using execvp. It needs to capture the results of the child process and parse them in the main process. It seems there is a way, using named pipes, and duping. I'm trying to hunt down a good example of this, but so far no luck. If anyone has any pointers, links and/or suggestions about this, I'd greatly appreciate it.
推荐答案
您不需要命名管道;未命名的管道可以正常工作.实际上,通常您可以只使用popen
而不是自己执行pipe
/fork
/dup
/exec
. popen
的工作方式如下(尽管您的libc
的实现可能会进行更多的错误检查):
You don't need named pipes; unnamed pipes work just fine. Actually, often you can just use popen
instead of doing the pipe
/fork
/dup
/exec
yourself. popen
works like this (though your libc
's implementation likely has more error checking):
FILE *popen(const char *command, const char *type) {
int fds[2];
const char *argv[4] = {"/bin/sh", "-c", command};
pipe(fds);
if (fork() == 0) {
close(fds[0]);
dup2(type[0] == 'r' ? 0 : 1, fds[1]);
close(fds[1]);
execvp(argv[0], argv);
exit(-1);
}
close(fds[1]);
return fdopen(fds[0], type);
}
这将创建一个未命名的管道和fork
s.在子级中,它将stdout(或stdin)重新连接到管道的一端,然后exec
子级.父级可以简单地从管道的另一端读取(或写入).
This creates an unnamed pipe, and fork
s. In the child, it reattaches stdout (or stdin) to one end of the pipe, then exec
s the child. The parent can simply read (or write) from the other end of the pipe.
这篇关于如何捕获execvp的输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!