一、FIFO 简介
无名管道由于没有名字,因此只能用于亲缘关系的进程间通信
命名管道提供了一个路径名与之关联,以 FIFO
的文件形式存在于文件系统中,这样即使进程不存在亲缘关系,只要可以访问该路径就能够彼此通信
FIFO
在文件系统中作为一个特殊的文件而存在,文件内容存放在内存中,当使用 FIFO
的进程退出后,FIFO
文件将继续保存在文件系统中以便以后使用
二、FIFO 示例代码
1. int mkfifo( const char *pathname, mode_t mode);
创建命名管道,后期操作把这个命名管道当做普通文件一样进行操作:open()、write()、read()、close()
通信过程中若写进程先退出了,就算命名管道里没有数据,调用 read()
函数读数据时不阻塞;若写进程又重新运行,则调用 read()
函数读数据时又恢复阻塞
mode:
文件的权限,与打开普通文件的 open()
函数中的 mode
参数相同
// 写进程
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc, char *argv[])
{
int fd;
mkfifo("my_fifo", 0666);
fd = open("my_fifo", O_WRONLY);
char send[128] = "Hello world";
write(fd, send, strlen(send));
printf("write to my_fifo buf=%s\n", send);
while(1);
return 0;
}
// 读进程
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
int main(int argc, char *argv[])
{
int fd;
mkfifo("my_fifo", 0666);
fd = open("my_fifo", O_RDONLY);
while (1)
{
char recv[128] = {0};
read(fd, recv, sizeof(recv));
printf("read from my_fifo buf=[%s]\n", recv);
sleep(1);
}
return 0;
}