【发布时间】:2016-03-17 09:25:23
【问题描述】:
我有两个进程。
先读后写。
其他人会先写然后读。
我想用两个管道来实现它。
这是我的实现
/***READ BEFORE WRITE*****/
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>
#define MAX_BUF 1024
int main()
{
int fd,fd1;
char buf[MAX_BUF];
char * myfifo = "/home/aditya/Desktop/myfifo";
char * mynewfifo = "/home/aditya/Desktop/mynewfifo";
mkfifo(mynewfifo, 0666);
printf("Read before writing\n");
printf("Before opening\n");
fd = open(myfifo, O_RDONLY);
fd1 = open(mynewfifo, O_WRONLY);
printf("After opening\n");
read(fd, buf, MAX_BUF);
printf("Received: %s\n", buf);
close(fd);
printf("reader is writing\n");
write(fd1, "Hi", sizeof("Hi"));
close(fd1);
unlink(mynewfifo);
return 0;
}
/**** Wriiting after Reading ******/
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>
int main()
{
int fd,fd1;
char * myfifo = "/home/aditya/Desktop/myfifo";
char * mynewfifo = "/home/aditya/Desktop/mynewfifo";
char buf[1024];
mkfifo(myfifo, 0666);
printf("writing before reading\n");
printf("Before opening\n");
fd = open(myfifo, O_WRONLY);
fd1=open(mynewfifo,O_RDONLY);
printf("After opening\n");
write(fd, "Hi", sizeof("Hi"));
close(fd);
printf("Writer is reading\n");
read(fd1, buf, 1024);
printf("Received: %s\n", buf);
close(fd1);
/* remove the FIFO */
unlink(myfifo);
return 0;
}
当我先运行“读后写”然后“写后读”时,它似乎工作。
但是当我反之亦然(即运行“写入后读取”)时,它们会打印“打开前”并继续运行。
请解释我做错了什么。
【问题讨论】:
标签: ipc named-pipes