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;
}
希望有人能指點我正確的方向。
並且您沒有想到驗證您的管道是否已正確創建將是一個好主意?總是檢查你的系統調用!錯誤不能被忽略。 – Stargateur