fifo_write.c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#define FIFO "/tmp/myfifo"
int main(void)
{
int nread = 0;
int filefd = open("../demoFIFOWrite/test.txt",O_RDONLY);
char buf[128]={0,};
//open调用的阻塞 是什么一回事呢?很简单,对于以只读方式(O_RDONLY)打开的FIFO文件,如果open调用是阻塞的(即第二个参数为O_RDONLY),除非有一个进程以写方式打开同一个FIFO,否则它不会返回;
int fifofd = open(FIFO, O_WRONLY);
if(fifofd == -1)
{
perror("open FIFO error");
return -1;
}
while((nread = read(filefd, buf, sizeof(buf))) > 0)
{
write(fifofd, buf, nread);
printf("write fifo %d data\n", nread);
}
return 0;
}
fifo_read.c
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <fcntl.h>
#define FIFO "/tmp/myfifo"
int main(void)
{
int fifofd = open(FIFO, O_RDONLY);
if(fifofd == -1)
{
perror("open FIFO error");
return -1;
}
char buf[128]={0,};
int nread = 0;
while((nread = read(fifofd, buf, sizeof(buf) - 1 )) > 0)
{
printf("%s",buf);
memset(buf, 0x00, sizeof(buf));
}
close(fifofd);
//write(STDOUT_FILENO, "\n", 1);
return 0;
}