一、前言
匿名管道的一个重大限制是它没有名字,因此,只能用于具有亲缘关系的进程间通信,在有名管道(named pipe或FIFO)提出后,该限制得到了克服。FIFO不同于管道之处在于它提供一个路径名与之关联,以FIFO的文件形式存在于文件系统中。这样,即使与FIFO的创建进程不存在亲缘关系的进程,只要可以访问该路径,就能够彼此通过FIFO相互通信(能够访问该路径的进程以及FIFO的创建进程之间),因此,通过FIFO不相关的进程也能交换数据。值得注意的是,FIFO严格遵循先进先出(first in first out),对管道及FIFO的读总是从开始处返回数据,对它们的写则把数据添加到末尾。它们不支持诸如lseek()等文件定位操作。
二、命名管道
1、创建
使用下面的函数创建命名管
<span style="font-weight: normal;">#include <sys/types.h>
#include <sys/stat.h>
int mkfifo(const char *filename, mode_t mode);</span>
该函数的第一个参数是一个普通的路径名,也就是创建后FIFO的名字。第二个参数则指定了文件的读写权限
<span style="font-weight: normal;">#include <sys/types.h>
#include <sys/stat.h>
int mkfifo(const char *filename, mode_t mode);</span>
二、访问
命名管道比匿名管道多了一个打开操作:open
一般来说,FIFO的打开操作有四中,阻塞读写和非阻塞读写,注:FIFO不能以O_RDWR方式打开
open(path, O_RDONLY);
open(path, O_RDONLY | O_NONBLOCK);
open(path, O_WRONLY);
open(path, O_WRONLY | O_NONBLOCK);
写FIFO的程序
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <limits.h>
#include <iostream>
#include <stdlib.h>
using namespace std;
const char *fifo_name = "/tmp/fifo_tmp";
const int BUF_SIZE=1024;
int main()
{
int fd;
if(access(fifo_name,F_OK)==-1)
{
int res = mkfifo(fifo_name,0777);
if(res != 0)
{
cout << "could not create fifo " << fifo_name << endl;
exit(1);
}
}
cout << "Process " << getpid() << " opening FIFO O_WRONLY" << endl;
fd = open(fifo_name,O_WRONLY);
cout << "Process " << getpid() << " result " << fd << endl;
if(fd == -1)
{
cout << "open fd failed" << endl;
exit(1);
}
else
{
int res;
char buf[BUF_SIZE];
while(1)
{
cout << ">";
memset(buf,0,sizeof(buf));
cin.getline(buf,BUF_SIZE);
res = write(fd,buf,strlen(buf));
if(res == -1)
{
cout << "write error on pipe" << endl;
exit(1);
}
if(strncmp(buf,"quit",4)==0)
break;
}
close(fd);
cout << "Process " << getpid() << " finished" << endl;
}
return 0;
}
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <limits.h>
#include <iostream>
#include <stdlib.h>
using namespace std;
const char *fifo_name = "/tmp/fifo_tmp";
const int BUF_SIZE=1024;
int main()
{
int fd;
cout << "Process " << getpid() << " opening FIFO O_RDONLY" << endl;
fd = open(fifo_name,O_RDONLY);
cout << "Process " << getpid() << " result " << fd << endl;
if(fd == -1)
{
cout << "open fd failed" << endl;
exit(1);
}
else
{
int res = 1;
char buf[BUF_SIZE];
while(1)
{
memset(buf,0,sizeof(buf));
res = read(fd,buf,BUF_SIZE);
cout << "Receive " << res << " bytes: " << buf << endl;
if(strncmp(buf,"quit",4)==0)
break;
}
close(fd);
cout << "Process " << getpid() << " finished" << endl;
}
return 0;
}
注意:当写端的数据长度小于 PIPE_BUF时,可以保证写入的原子性,即要么全部写入,要么全部不写入。如果,写端数据长度大于PIPE_BUF,则不能保证。