2017-10-15 126 views
0

我想從兩個兄弟進程的Child1到Child3發送一個字符串「Hi」。代碼運行,但是我沒有收到來自Child3中Child1的輸入。使用命名管道在兩個進程之間發送字符串

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

#define MSGSIZE 1024 

int main (int argc, char *argv[]){ 

    int fd; 
    char * myfifo = "/desktop/myfifo"; 
    char l[MSGSIZE]; 
    pid_t child1, child3; 
    mkfifo(myfifo, 0666); 
    child1 = fork(); 

if (child1 == 0) { 

    printf("I am Child 1: %d \n", (int)getpid()); 
      fd = open(myfifo, O_WRONLY); 
      write(fd, "Hi", MSGSIZE); 
      close(fd); 
    } 

else { 

    if (child1 > 0) { 
     printf("I am parent: %d \n", (int)getpid()); 

     wait(0); 
    } 

    child3 = fork(); 

    if (child3 == 0) { 
     printf("I am Child 3: %d \n", (int)getpid()); 

     fd = open(myfifo, O_RDONLY); 
     read(fd, l, MSGSIZE); 
     printf("Received: %s \n", l); 

     close(fd); 
    } 
} 
    wait(0); 
    unlink(myfifo); 
    return 0; 
} 

希望有人能指點我正確的方向。

+0

並且您沒有想到驗證您的管道是否已正確創建將是一個好主意?總是檢查你的系統調用!錯誤不能被忽略。 – Stargateur

回答

0

除非你正在做非阻塞IO,否則打開FIFO的一端會阻塞,直到另一端也打開。因此child1塊的open(2)呼叫,直到child3打開它們的管道末端。但是,在之前,您還在父進程中調用wait(2),您將child3分叉。

所以,你有一個僵局:家長在等待child1child3,但child1正在等待child3打開管道的另一端。

您可以至少用兩種方法解決這個問題。首先,在分叉第二個子進程後,只需撥打wait(2)。另一種方法是在父進程中創建一個pipe(2),讓子進程繼承這些描述符並以這種方式將數據傳遞給對方。

相關問題