进程间通信(IPC)之-----------fifo

1、

无名管道,由于没有名字,只能用于亲缘关系的进程间通信多。为了克服这个缺点,提出了命名管道(FIFO),也叫有名管道、FIFO 文件。

命名管道(FIFO)不同于无名管道之处在于它提供了一个路径名与之关联,以 FIFO 的文件形式存在于文件系统中,这样,即使与 FIFO 的创建进程不存在亲缘关系的进程,只要可以访问该路径,就能够彼此通过 FIFO 相互通信,因此,通过 FIFO 不相关的进程也能交换数据。

命名管道(FIFO)和无名管道(pipe)有一些特点是相同的,不一样的地方在于:

#include <sys/types.h>
#include <sys/stat.h>
原型:
int mkfifo( const char *pathname, mode_t mode);

2、fd = open("my_fifo", O_WRONLY); //等着只读管道的特点只读等只写,只写等只读

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

write_fifo.c


#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;

}

readd_fifo.c


#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;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值