簡體   English   中英

C ++既輸入又輸出管道到外部程序

[英]C++ both input and output pipe to the external program

我試圖用一些輸入調用外部程序,並在程序中檢索它的輸出。

看起來像;

(一些輸入)| (外部程序)| (檢索輸出)

我首先考慮使用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
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM