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;
}