簡體   English   中英

Linux管道,fork和execlp:如何將值寫入流1中

[英]Linux pipe, fork and execlp: how to get the value written into stream 1

我使用函數(L)通過execlp()執行另一個程序(K execlp() 在K程序中,結果寫入流1:

write(1, (char *)&o, sizeof(int));

因為在execlp() ,L的剩余部分將不會被執行,我怎樣才能得到在流1中寫入的結果?

不要問我為什么需要這樣做。 這是項目的要求。

我跟着你們的建議,但現在的問題是,K程序獲取參數的方式來自流(一個標准流,另一個流),我使用管道將參數寫入相應的流(由父進程完成) )。

在子exec之后,在父部分中,我從流0讀取(K程序將其結果寫回流1中)。 但我能得到的是父母寫入流中的內容,而不是K程序寫回的內容。 怎么了? 我需要添加另一個管道嗎?

謝謝!!

Jonathan Leffler在評論中提到的關鍵見解是,在調用execlp()之前,需要fork運行L的程序。

在fork之后,父execlp()繼續執行L的其余部分,並且子execlp()通過調用execlp()變換到程序K ,除非出現錯誤,否則永遠不會返回。

因此,“L的剩余部分將不會被執行”的斷言是不正確的。 如果正確編寫函數L它將在父進程中執行。

更新 :由於OP提出了更具體的問題,我接着回答這個問題。

如果要檢索子進程寫入stdout (fd 1)的內容,則需要在fork之前創建一個新管道,並將此管道的寫入端復制到子項的stdout

這是一個示例程序,稍微修改了管道手冊頁

#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

int
main(int argc, char *argv[])
{
    int pipefd[2];
    pid_t cpid;
    char buf;

    if (pipe(pipefd) == -1) {
        perror("pipe");
        exit(EXIT_FAILURE);
    }

    cpid = fork();
    if (cpid == -1) {
        perror("fork");
        exit(EXIT_FAILURE);
    }

    if (cpid == 0) {    /* Child writes into the pipe */
        close(pipefd[0]);          /* Close unused read end */

        // Copy the writing end of the pipe into STDOUT for the child.
        dup2(pipefd[1], STDOUT_FILENO);

        // Execute your program L here, and its stdout will be captured by the pipe.
        const char* message = "Child is speaking to stdout!";
        write(STDOUT_FILENO, message, strlen(message));
        write(STDOUT_FILENO, "\n", 1);


        close(pipefd[1]);
        _exit(EXIT_SUCCESS);

    } else {            /* Parent reads child's stdout  from the pipe */
        close(pipefd[1]);          /* Close unused write end */

        // Here the parent process is reading the child's stdout.
        while (read(pipefd[0], &buf, 1) > 0)
            write(STDOUT_FILENO, &buf, 1);
        wait(NULL);                /* Wait for child */
        exit(EXIT_SUCCESS);
    }
}

暫無
暫無

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

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