标签:blog http io os 使用 ar 文件 数据 sp
FIFO又被称为命名管道,未命名的管道只能在两个相关的进程之间使用,而这两个相关的进程还要有一个共同创建了它们的祖先进程,但是FIFO,不相关的进程之间也能交换数据。
FIFO是一种文件类型。通过stat结构的st_mode成员的编码可以知道文件是否是FIFO类型,在linux下查看自己创建的FIFO文件:

创建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读取程序:
#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,在命令提示符下输入:
$ ./a.out & [1] 4768 //这里是进程ID回现
将a.out程序作为一个后台进程运行。
在终端创建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进行通信。
$ 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两个进程之间的通信已经完成了。
标签:blog http io os 使用 ar 文件 数据 sp
原文地址:http://my.oschina.net/xlplbo/blog/325502