FIFO又被称为命名管道,未命名的管道只能在两个相关的进程之间使用,而这两个相关的进程还要有一个共同建立了它们的祖先进程,可是FIFO,不相关的进程之间也能交换数据。
linux
FIFO是一种文件类型。经过stat结构的st_mode成员的编码能够知道文件是不是FIFO类型,在linux下查看本身建立的FIFO文件:
shell
建立FIFO相似于建立文件,也存在于文件系统之中。定义以下:函数
#include <sys/stat.h> int mkfifo(const char* path, mode_t mode); int mkfifoat(int fd, const char* path, mode_t mode);
两个函数返回值:若成功返回0,失败则返回-1,使用方法参照open函数。编码
编写本身的后台FIFO读取程序:.net
#include <stdio.h> #include <sys/stat.h> #include <errno.h> #include <fcntl.h> int main(int argc, char* argv[]) { int fd; int nRead; char szBuff[128]; const char* szPath = "/tmp/fifo"; //临时目录的一个fifo,能够在程序里建立也能够在shell里建立 fd = open(szPath, O_RDONLY, 0); if (-1 == fd) { printf("open fifo error\n"); goto exit; } while(1) { if((nRead = read(fd, szBuff, sizeof(szBuff))) == -1) { if (errno == EAGAIN) printf("no data\n"); } if (szBuff[0] == 'Q') break; szBuff[nRead] = '\0'; printf("data:%s\n", szBuff); sleep(1); } exit: return 0; }
使用cc fifo.c 编译成功后获得a.out,在命令提示符下输入:code
$ ./a.out & [1] 4768 //这里是进程ID回现
将a.out程序做为一个后台进程运行。blog
在终端建立fifo(也能够在程序内建立):进程
$ mkfifo /tmp/fifo $ ls -ln /tmp/fifo prw-rw-r-- 1 1001 1001 0 10月 9 22:04 /tmp/fifo
咱们使用linux自带的tee回现程序和a.out进行通讯。get
$ tee /tmp/fifo //标准输出到fifo hello fifo! // 这里是我输入的 hello fifo! // 这里是tee回现功能 data:hello fifo! // 这里是a.out回应 q q data:q // 这里是a.out回应 Q Q hello fifo? hello fifo? [1]+ 完成 ./a.out
至此a.out与tee两个进程之间的通讯已经完成了。it