Linux C FIFO(有名管道)通信

FIFO(有名管道)与Pipe(无名管道)都是通过内核缓冲区来进行通信,Pipe(无名管道)只能用于有缘进程之间的通信,而FIFO(有名管道)亦可 用于无缘进程之间的通信。创建一个FIFO(有名管道),其也拥有像文件名那样的名称,可以通过 ls -l 命令查看,文件类型为p。
在这里插入图片描述

FIFO写端:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#define MX_SIZE 1024
int main()
{
	int fd=-1;
	int n=-1;
	char buf[MX_SIZE]="hello";
	mkfifo("./FIFO",0664); //创建FIFO FIFO的权限 = 0664&~umasK(0022)
    fd = open("./FIFO",O_WRONLY);   //只写
	if(fd < 0)printf("open error\n");
	n = write(fd,buf,MX_SIZE);
	if(n < 0)printf("write error\n");
	return 0;
}

写端以只写(O_WRONLY)的方式打开FIFO,调用write函数时,会阻塞到读端打开为止。如果以读写的方式打开(O_RDWR),就不会阻塞。

FIFO读端:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#define MAX_SIZE 1024
int main()
{
	int fd;
	char *buf;
	int n;
    fd = open("./FIFO",O_RDONLY);
    if(fd < 0)printf("open error\n");
	n = read(fd,buf,MAX_SIZE);
	if(n < 0)printf("write error\n");
	printf("buf=%s\n",buf);
	return 0;
}

通信结果:

在这里插入图片描述

要以非阻塞的方式来打开FIFO,须在open函数中指定O_NONBLOCK参数。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章