C++ 向外部程序提供输入和输出管道

2024-01-10

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

它将看起来像;

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

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

有没有什么简单的方法可以处理这种事情linux?

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

有什么解决办法吗?谢谢。


在Linux上你可以使用pipe http://man7.org/linux/man-pages/man2/pipe.2.html功能:打开两个新管道,每个方向一个,然后使用创建一个子进程fork https://linux.die.net/man/2/fork之后,您通常会关闭未使用的文件描述符(在父管道上读取端,在管道的子管道上写入端,以便父管道发送到子管道,反之亦然,对于其他管道),然后使用execve http://man7.org/linux/man-pages/man2/execve.2.html或其前端之一。

If you dup2 https://linux.die.net/man/2/dup管道的文件描述符到标准控制台文件句柄(STDIN_FILENO/STDOUT_FILENO;每个过程分开),你should甚至能够使用std::cin/std::cout用于与其他进程通信(您可能只想为子进程执行此操作,因为您可能希望将控制台保留在父进程中)。不过,我还没有对此进行过测试,所以这留给你了。

完成后,你还wait or waitpid https://linux.die.net/man/2/wait让您的子进程终止。可能类似于以下代码:

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
    }
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

C++ 向外部程序提供输入和输出管道 的相关文章

随机推荐