使用命名管道在两个进程之间发送字符串
问题描述:
我想从两个兄弟进程的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;
}
希望有人能指点我正确的方向。
答
除非你正在做非阻塞IO,否则打开FIFO的一端会阻塞,直到另一端也打开。因此child1
块的open(2)
呼叫,直到child3
打开它们的管道末端。但是,在之前,您还在父进程中调用wait(2)
,您将child3
分叉。
所以,你有一个僵局:家长在等待child1
叉child3
,但child1
正在等待child3
打开管道的另一端。
您可以至少用两种方法解决这个问题。首先,在分叉第二个子进程后,只需拨打wait(2)
。另一种方法是在父进程中创建一个pipe(2)
,让子进程继承这些描述符并以这种方式将数据传递给对方。
并且您没有想到验证您的管道是否已正确创建将是一个好主意?总是检查你的系统调用!错误不能被忽略。 – Stargateur