1、简介
对于普通的未命名pipe,两个不相关的进程是无法通信的。但是对于命名通道FIFO而言,即便是两个不相关的进程也可以实现进程间通信。
2、操作 FIFO
FIFO在文件系统中表现为一个文件,大部分的系统文件调用都可以用在FIFO上面,比如:read,open,write,close,unlink,stat等函数。但是seek等函数不能对FIFO调用。
可以调用open函数打开命名管道,但是有两点要注意
1)不能以O_RDWR模式打开命名管道FIFO文件,否则其行为是未定义的,管道是单向的,不能同时读写;
2)就是传递给open调用的是FIFO的路径名,而不是正常的文件
打开FIFO文件通常有四种方式:
open(pathname, O_RDONLY); //1 只读、阻塞模式
open(pathname, O_RDONLY | O_NONBLOCK); //2 只读、非阻塞模式
open(pathname, O_WRONLY); //3 只写、阻塞模式
open(pathname, O_WRONLY | O_NONBLOCK); //只写、非阻塞模式
注意阻塞模式open打开FIFO:
1)当以阻塞、只读模式打开FIFO文件时,将会阻塞,直到其他进程以写方式打开访问文件;
2)当以阻塞、只写模式打开FIFO文件时,将会阻塞,直到其他进程以读方式打开文件;
3)当以非阻塞方式(指定O_NONBLOCK)方式只读打开FIFO的时候,则立即返回。当只写open时,如果没有进程为读打开FIFO,则返回-1,其errno是ENXIO。
3、代码使用操作
(1)阻塞管道读写
Read进程代码如下:
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>int main(int argc, char* argv[])
{
int ret = mkfifo("my_fifo",0777);
if (ret == -1)
{
printf("make fifo failed!\n");
return 1;
}char buf[256] = {0};
int fd = open("my_fifo",O_RDONLY);
read(fd,buf,256);
printf("%s\n",buf);
close(fd);
unlink("my_fifo");
return 0;
}
Write进程代码如下:
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>int main(int argc, char* argv[])
{
char *buf = "i am write process\n";
int fd = open("my_fifo",O_WRONLY);
write(fd,buf,strlen(buf));
close(fd);
return 0;
}
首先启动read进程,创建fifo,当前目录下会生出一个名字为“my_fifo”的文件,然后启动write进程,运行结果如下:
结论:当write进程没有以O_WRONLY模式open命名管道时,read进程在以O_RDONLY模式open命名管道的时候会阻塞。反过来也是这样。
(2)非阻塞管道读写
Read进程代码如下:
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>int main(int argc, char* argv[])
{
int ret = mkfifo("my_fifo",0777);
if (ret == -1)
{
printf("make fifo failed!\n");
return 1;
}char buf[256] = {0};
int fd = open("my_fifo",O_RDONLY | O_NONBLOCK);
// sleep(5);
read(fd,buf,256);
printf("%s\n",buf);
close(fd);
unlink("my_fifo");
return 0;
}
Write进程代码如下:
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>int main(int argc, char* argv[])
{
char *buf = "i am write process\n";
int fd = open("my_fifo",O_WRONLY | O_NONBLOCK);
write(fd,buf,strlen(buf));
close(fd);
return 0;
}
直接启动Read进程,open函数将不会阻塞,read函数读取到0个字节数据,程序退出。
将sleep(5)的注释去掉,再次启动Read进程,马上启动Write进程,Read进程会读取到Write进程写入fifo的数据并打印,然后退出。
结论:flags=O_RDONLY|O_NONBLOCK:如果此时没有其他进程以写的方式打开FIFO,open也会成功返回,此时FIFO被读打开,而不会返回错误。
经测试:flags=O_WRONLY|O_NONBLOCK:立即返回,如果此时没有其他进程以读的方式打开,open会失败打开,此时FIFO没有被打开,返回-1。
文章引用:Linux进程间通信-命名管道深入理解