Linux:使用管道标准输入/标准输出执行子进程
使用 Linux 和 C++,我想要一个执行以下操作的函数:
string f(string s)
{
string r = system("foo < s");
return r;
}
显然上面的方法不起作用,但你明白了。我有一个字符串 s
,我想将其作为应用程序“foo”的子进程执行的标准输入传递,然后我想将其标准输出记录到字符串 r< /code> 然后返回它。
我应该使用 Linux 系统调用或 POSIX 函数的什么组合? 我使用的是 Linux 3.0,不需要使用旧系统的解决方案。
Using Linux and C++, I would like a function that does the following:
string f(string s)
{
string r = system("foo < s");
return r;
}
Obviously the above doesn't work, but you get the idea. I have a string s
that I would like to pass as the standard input of a child process execution of application "foo", and then I would like to record its standard output to string r
and then return it.
What combination of Linux syscalls or POSIX functions should I use?
I'm using Linux 3.0 and do not need the solution to work with older systems.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
eerpini 提供的代码不能按编写的方式工作。请注意,例如,随后使用在父级中封闭的管端。查看
该关闭描述符的后续写入。这只是换位,但它表明这段代码从未被使用过。以下是我测试过的版本。不幸的是,我改变了代码风格,所以这没有被接受为对 eerpini 代码的编辑。
唯一的结构变化是我只重定向子级中的 I/O(注意 dup2 调用仅在子级路径中。)这非常重要,因为否则父级的 I/O 会变得混乱。感谢 eerpini 提供的最初答案,我在开发这个答案时使用了它。
The code provided by eerpini does not work as written. Note, for example, that the pipe ends that are closed in the parent are used afterwards. Look at
and the subsequent write to that closed descriptor. This is just transposition, but it shows this code has never been used. Below is a version that I have tested. Unfortunately, I changed the code style, so this was not accepted as an edit of eerpini's code.
The only structural change is that I only redirect the I/O in the child (note the dup2 calls are only in the child path.) This is very important, because otherwise the parent's I/O gets messed up. Thanks to eerpini for the initial answer, which I used in developing this one.
由于您想要双向访问该进程,因此您必须使用管道在幕后显式执行 popen 所做的操作。我不确定这是否会在 C++ 中改变,但这里有一个纯 C 示例:
实际上,您可以这样做:
dup() 用于在文件描述符表中创建重复条目。而 dup2() 改变了描述符指向的内容。
注意:正如 Ammo@ 在他的解决方案中提到的,我上面提供的或多或少是一个模板,如果您只是尝试执行代码,它就不会运行,因为显然缺少 exec* (函数系列),所以child 几乎会在 fork() 之后立即终止。
Since you want bidirectional access to the process, you would have to do what popen does behind the scenes explicitly with pipes. I am not sure if any of this will change in C++, but here is a pure C example :
Effectively you do this :
dup() is used to create a duplicate entry in the file descriptor table. While dup2() changes what the descriptor points to.
Note : As mentioned by Ammo@ in his solution, what I provided above is more or less a template, it will not run if you just tried to execute the code since clearly there is a exec* (family of functions) missing, so the child will terminate almost immediately after the fork().
Ammo 的代码存在一些错误处理错误。子进程在 dup 失败后返回而不是退出。也许子副本可以替换为:
Ammo's code has some error handling bugs. The child process is returning after dup failure instead of exiting. Perhaps the child dups can be replaced with: