一、FIFO简介
1、API:
#include <sys/types.h>
#include <sys/stat.h>
int mkfifo(const char * pathname,mode_t mode);
返回: 成功返回0,出错返回-1
2、
FIFO只要有适当的访问权限,可用在任何进程之间通信(有关系或者没关系的进程)。
本质是内核中的一块缓存,另外在文件系统中以一个特殊的设备文件(管道文件)存在,文件系统中只有一个索引块存放文件的路径,数据块在内核中。
命名管道FIFO必须读和写同时打开,单独写或者单独读会引发阻塞。
命令mkfifo也可创建命名管道。
对FIFO的操作与普通文件一样,open、close、read、write、unlink等api都可用。
二、代码示例
通过外部mkfifo创建一个管道,并将管道的名字作为两个进程main函数的参数,在这两个进程中完成读写通信。
fifo_read.c
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
int main(int argc,char *argv[])
{
if(argc < 2)
{
printf("usage: a.out fifoname\n");
exit(-1);
}
printf("open fifo:\n");
int fd = open(argv[1],O_RDONLY);
if(fd < 0)
{
printf("fifo open error\n");
exit(-1);
}
else
{
printf("fifo open succcess:%d\n",fd);
char buf[256] = {0};
while(read(fd,buf,sizeof(buf)) > 0)
{
printf("%s",buf);
memset(buf,0,sizeof(buf));
}
}
close(fd);
exit(0);
}
fifo_write.c
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
int main(int argc,char*argv[])
{
if(argc < 2)
{
printf("usage: ./a.out mkfifo\n");
exit(-1);
}
printf("open fifo :\n");
int fd = open(argv[1],O_WRONLY);
if(fd < 0)
{
printf("fifo open error\n");
exit(-1);
}
else
{
printf("fifo open success:%d\n",fd);
char *str = "abcdefghijklmnopqrstuvwxyz";
write(fd,str,strlen(str));
close(fd);
}
exit(0);
}
创建一个管道com.pipe,并对两个进程进行传参