C++外部程序的输入和输出管道



我正在尝试使用一些输入调用外部程序并在程序中从中检索输出。

它将看起来像;

(一些输入( |(外部程序( |(检索输出(

我首先想到使用popen()但似乎是不可能的,因为管道不是双向的

有没有简单的方法可以在Linux中处理这种东西?

我可以尝试制作一个临时文件,但如果可以在不访问磁盘的情况下清楚地处理它,那就太好了。

有什么解决方案吗?谢谢。

在 Linux 上,您可以使用pipe函数:打开两个新管道,每个方向一个,然后使用fork创建一个子进程,然后,您通常关闭未使用的文件描述符(读取父管道的结束,在子管道上写入结束,用于父管道发送到子管道,反之亦然对于另一个管道(,然后使用execve或其前端之一启动应用程序。

如果将管道的文件描述符 dup2 到标准控制台文件句柄(STDIN_FILENO/STDOUT_FILENO;每个进程分别(,您甚至应该能够使用std::cin/std::cout与其他进程进行通信(您可能只想为子进程执行此操作,因为您可能希望将控制台保留在父进程中(。不过,我没有测试过这个,所以留给你。

完成后,您还需要waitwaitpid子进程才能终止。可能类似于以下代码段:

int pipeP2C[2], pipeC2P[2];
// (names: short for pipe for X (writing) to Y with P == parent, C == child)
if(pipe(pipeP2C) != 0 || pipe(pipeC2P) != 0)
{
// error
// TODO: appropriate handling
}
else
{
int pid = fork();
if(pid < 0)
{
// error
// TODO: appropriate handling
}
else if(pid > 0)
{
// parent
// close unused ends:
close(pipeP2C[0]); // read end
close(pipeC2P[1]); // write end
// use pipes to communicate with child...
int status;
waitpid(pid, &status, 0);
// cleanup or do whatever you want to do afterwards...
}
else
{
// child
close(pipeP2C[1]); // write end
close(pipeC2P[0]); // read end
dup2(pipeP2C[0], STDIN_FILENO);
dup2(pipeC2P[1], STDOUT_FILENO);
// you should be able now to close the two remaining
// pipe file desciptors as well as you dup'ed them already
// (confirmed that it is working)
close(pipeP2C[0]);
close(pipeC2P[1]);
execve(/*...*/); // won't return - but you should now be able to
// use stdin/stdout to communicate with parent
}
}

最新更新