write_fifo.c
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<string.h>
#include<stdlib.h>
#include<errno.h>
int main(int argc, const char *argv[])
{
char buf[64] = {0};
int fd;
if(argc != 2)
{
fprintf(stderr,"usage:%s fifo\n",argv[1]);
return -1;
}
if(mkfifo(argv[1],0666)< 0 && errno != EEXIST)
{
perror("Fail to mkfifo");
return -1;
}
fd = open(argv[1],O_RDWR);
while(1)
{
fgets(buf,sizeof(buf),stdin);
write(fd,buf,sizeof(buf));
if(!strncmp(buf,"quit",4))
{
exit(0);
}
}return 0;
}
read_file.c
#include<stdio.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<string.h>
#include<stdlib.h>
#include<errno.h>
int main(int argc, const char *argv[])
{
char buf[64] = {0};
int fd;
if(argc != 2)
{
fprintf(stderr,"usage:%s fifo\n",argv[1]);
return -1;
}fd = open(argv[1],O_RDWR);
while(1)
{
read(fd,buf,sizeof(buf));
if(!strncmp(buf,"quit",4))
{
exit(0);
}
printf("Read:%s\n",buf);
}return 0;
}
输出结果: