问题:发现read文件运行之后就停不下来了,一直在获取
read.c文件
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include<errno.h>
#include <fcntl.h>
// int mkfifo(const char *pathname, mode_t mode);
int main()
{
char buf[30] = {0};
int nread = 0;
if( (mkfifo("./file",0600) == -1) && errno!=EEXIST){
printf("mkfifo failuer\n");
perror("why");
}
int fd = open("./file",O_RDONLY);
printf("open success\n");
while(1){
nread = read(fd,buf,30);
printf("read %d byte from fifo,context:%s\n",nread,buf);
}
close(fd);
return 0;
}
write.c文件
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include<errno.h>
#include <fcntl.h>
#include <string.h>
// int mkfifo(const char *pathname, mode_t mode);
int main()
{
int cnt = 0;
char *str = "message from fifo";
int fd = open("./file",O_WRONLY);
printf("write open success\n");
while(1){
write(fd, str, strlen(str));
sleep(1);
if(cnt == 5){
break;
}
}
close(fd);
return 0;
}
---------------------------------------------------------------------------------------------------------------------------------
想法一:修改write()的函数
结果却发现输出5个后马上刷屏了
想法二(正确的):得从read.c文件入手,毕竟是输出(read)的问题,不是输入(write)的问题
修改后的代码 read.c
最终的运行结果: