fifo_write.c
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#define MYFIFO "/tmp/myfifo" /*有名管道文件标识*/
#define QUIT_STR "quit"
int
main(void){
int fd;
char buf[100]={0};
struct stat statbuf;
if( -1 == access(MYFIFO, F_OK)){ /*检查文件是否存在*/
if(-1==mkfifo(MYFIFO, 0666)){ /*创建管道文件*/
perror("mkfifo");
exit(EXIT_FAILURE);
}
}else{ /*文件存在*/
if(-1==lstat(MYFIFO, &statbuf)){ /*获取文件的类型*/
perror("lstat");
}
if(!S_ISFIFO(statbuf.st_mode)){ /*判断是否是管道文件*/
unlink(MYFIFO); /*不是管道文件,删除*/
if(-1==mkfifo(MYFIFO, 0666)){ /*创建管道文件*/
perror("mkfifo");
exit(EXIT_FAILURE);
}
}
}
if((fd=open(MYFIFO, O_WRONLY))==-1){
perror("open_write");
exit(EXIT_FAILURE);
}
while(1){
bzero(buf,100);
fgets((char *)buf, sizeof(buf)-1, stdin);
//fgets写成替换成read(STDIN_FILENO, buf, sizeof(buf)-1);
write(fd, buf, sizeof(buf));
if(!strncasecmp(buf, QUIT_STR, strlen(QUIT_STR))){ /*输入quit退出(不区分大小写)*/
break;
}
}
close(fd); /*关闭文件*/
return 0;
}
fifo_read.c
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <fcntl.h>
#define MYFIFO "/tmp/myfifo" /*有名管道文件标识*/
#define QUIT_STR "quit"
int
main(void){
int fd;
char buf[100]={0};
struct stat statbuf;
if( -1 == access(MYFIFO, F_OK)){ /*检查文件是否存在*/
if(-1==mkfifo(MYFIFO, 0666)){ /*创建管道文件*/
perror("mkfifo");
exit(EXIT_FAILURE);
}
}else{ /*文件存在*/
if(-1==lstat(MYFIFO, &statbuf)){ /*获取文件的类型*/
perror("lstat");
}
if(!S_ISFIFO(statbuf.st_mode)){ /*判断是否是管道文件*/
unlink(MYFIFO); /*不是管道文件,删除*/
if(-1==mkfifo(MYFIFO, 0666)){ /*创建管道文件*/
perror("mkfifo");
exit(EXIT_FAILURE);
}
}
}
if((fd=open(MYFIFO, O_RDONLY))==-1){
perror("open_read");
exit(EXIT_FAILURE);
}
while(1){
bzero(buf,100);
read(fd, buf, sizeof(buf));
printf("%s",buf);
if(!strncasecmp(buf, QUIT_STR, strlen(QUIT_STR))){ /*输入quit退出(不区分大小写)*/
break;
}
}
close(fd);
return 0;
}