簡體   English   中英

用多個子進程進行C讀寫

[英]C reading and writing with multiple child processes

通過C中的父進程,我正在運行3個子進程,每個子進程都執行一個程序。

  • 程序1獲取標准輸入(用戶輸入)並將其打印到標准輸出。
  • 程序2獲取標准輸入(應來自程序1),對其進行修改並將其打印為標准輸出。
  • 程序3獲取標准輸入(應該來自程序2),對其進行修改並打印到標准輸出

我正在獲取program3的輸出,但是未顯示對program 2的修改。

以下是父級的相關代碼:

if((child1 = fork()) < 0){
    /*fatal*/
}
else if(child1 == 0){ //inside child 1
    dup2(pipe1[1], 1); //child 1 uses pipe1[1] for writing
    close(pipe1[0]);

    execl("program1.out", (char *)0);
}
else{
    if((child2 = fork()) <0){
        /*fatal*/
    }
    else if(child2 == 0){ //inside child 2
        close(pipe1[1]);
        dup2(pipe1[0], 0); //child2 uses pipe1[0] for reading
        dup2(pipe2[1], 1); //child2 uses pipe[1] for writing

        execl("program2.out", (char *)0);
    }
    else{
        if((child3 = fork()) <0){
            /*fatal*/
        }
        else if(child3 == 0){ //inside child 3
            close(pipe2[1]);
            close(pipe1[0]);

            execl("program3.out", (char *)0);
        }
        else{ //inside parent
            wait(NULL);
        }
    }   
}

程序使用fgets和printf進行讀取/寫入。

我已經檢查了先前的問題,但找不到我做錯了什么。 有任何想法嗎?

Child3需要執行以下操作:

dup2(pipe2[0], 0); // child3 uses pipe2[0] for reading

您還需要關閉一個孩子沒有在每個孩子中使用的所有管道。 因此,child1需要:

close(pipe2[0]);
close(pipe2[1]);

child2需要:

close(pipe2[0]);

而child3需要:

close(pipe1[0]);
close(pipe1[1]);
close(pipe2[1]);

在分叉所有孩子之后,家長需要關閉所有管道。

所有這些關閉都是必需的,以便當管道中的上一個程序關閉管道時,進程將讀取EOF ,因為直到打開管道的所有進程都將其關閉,管道才真正關閉。

暫無
暫無

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

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