linux c++(fifo有名管道通信)

open注意事项,打开fifo文件的时候,read端会阻塞等待write端open,write端同理,也会阻塞等待另外一端打开

FIFO 有名管道,实现无血缘关系进程通信
	创建一个管道的伪文件
		命令方式: mkfifo myfifo
		系统函数: int mkfifo(const char *pahtname,mode_t 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;
	int ret;
	ret = mkfifo("my_fifo", 0666);//创建命名管道
	if(ret != 0)
	{
		perror("mkfifo");
	}

	printf("before open\n");
	fd = open("my_fifo", O_WRONLY); //等着只读
	if(fd < 0)
	{
		perror("open fifo");
	}
	printf("after open\n");
	printf("before write\n");

	// 5s后才往命名管道写数据,没数据前,读端read()阻塞
	sleep(5);
	char send[100] = "Hello Mike";
	write(fd, send, strlen(send));
	printf("write to my_fifo buf=%s\n", send);
	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;
	int ret;
	ret = mkfifo("my_fifo", 0666); //创建命名管道
	if(ret != 0)
	{
		perror("mkfifo");
	}
	printf("before open\n");
	fd = open("my_fifo", O_RDONLY);//等着只写
	if(fd < 0)
	{
		perror("open fifo");
	}
	printf("after open\n");
	printf("before read\n");
	char recv[100] = {0};
	//读数据,命名管道没数据时会阻塞,有数据时就取出来
	read(fd, recv, sizeof(recv)); 
	printf("read from my_fifo buf=[%s]\n", recv);
	return 0;

}

  • open() 以只读方式打开 FIFO 时,要阻塞到某个进程为写而打开此 FIFO open() 以只写方式打开 FIFO时,要阻塞到某个进程为读而打开此 FIFO。 简单一句话,只读等着只写,只写等着只读,只有两个都执行到,才会往下执行。

  • 假如 FIFO 里没有数据,调用 read() 函数从 FIFO 里读数据时 read() 也会阻塞。这个特点和无名管道是一样的。

  • 通信过程中若写进程先退出了,就算命名管道里没有数据,调用 read() 函数从 FIFO 里读数据时不阻塞;若写进程又重新运行,则调用 read() 函数从 FIFO 里读数据时又恢复阻塞。

  • 通信过程中,读进程退出后,写进程向命名管道内写数据时,写进程也会(收到 SIGPIPE 信号)退出。

  • 调用 write() 函数向 FIFO 里写数据,当缓冲区已满时 write() 也会阻塞

(学习复习资料)本文内容来自:https://blog.csdn.net/tennysonsky/article/details/45847107

posted on 2021-05-05 00:06  lodger47  阅读(755)  评论(0)    收藏  举报

导航