【发布时间】:2017-10-15 06:08:28
【问题描述】:
我正在尝试从 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;
}
希望有人能指出正确的方向。
【问题讨论】:
-
您认为验证您的管道是否已正确创建不是一个好主意吗?始终检查您的系统调用!错误不容忽视。
标签: c ipc named-pipes