有名管道(FIFO)
命名管道也被称为FIFO文件,是一种特殊的文件。由于linux所有的事物都可以被视为文件,所以对命名管道的使用也就变得与文件操作非常统一。
原型:int mkfifo(const char *filename, mode_t mode);
有名管道通信:
读取端:
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
int main()
{
char buf[30] = {0};
int nread;
if((mkfifo("./file",0600) == -1) && errno != EEXIST){
printf("make file fail");
perror("why");
}
int fd = open("./file",O_RDONLY);
printf("open success\n");
while(1){
sleep(1);
nread = read(fd,buf,30);
printf("read %d bate,context:%s\n",nread,buf);
}
close(fd);
return 0;
}
写入端:
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <fcntl.h>
int main()
{
char *wbuf = “this is write”;
int fd;
fd = open("./file",O_RDWR);
while(1){
sleep(1);
write(fd,wbuf,strlen(wbuf));
}
close(fd);
输出结果为: