有名管道FIFO示例

shell中本身存在mkfifo的命令,但是本质也是调用mkfifo()函数实现。

与无名管道相比,无非是多了一个管道文件用以操作。

先在shell中通过mkfifo创建一个管道文件mkfifo s.pipe,执行read s.pipe和write s.pipe。

读端:

/*************************************************************************
    > File Name: read_fifo.c
    > Author: CC
    > Mail: 6828620@163.com 
    > Created Time: 2018年09月08日 星期六 23时01分04秒
 ************************************************************************/

#include<stdio.h>
#include<stdlib.h>
#include<fcntl.h>
#include<unistd.h>
#include<string.h>
int main(int argc,char *argv[])
{
	if(argc < 2){
		printf("Usage: %s fifo \n",argv[0]);
		exit(1);
	}

	printf("open fifo read .......\n");

	int fd = open(argv[1],O_RDONLY);
	if(fd < 0){
		perror("open fifo error!\n");
		exit(1);
	}else{
		printf("open file success: %d\n",fd);
	}
	//从命名管道中读取数据
	char buf[512];
	memset(buf,0,sizeof(buf));
	while(read(fd,buf,sizeof(buf)) < 0){
		perror("read error!\n");
		exit(1);
	}
	printf("read file %s\n",buf);
	close(fd);
	return 0;

}

写端:

/*************************************************************************
    > File Name: write_fifo.c
    > Author: CC
    > Mail: 6828620@163.com 
    > Created Time: 2018年09月08日 星期六 23时07分51秒
 ************************************************************************/

#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<fcntl.h>
#include<string.h>

int main(int argc,char *argv[])
{
	if(argc < 2){
		printf("Usage: %s fifo\n",argv[0]);
		exit(1);
	}
	printf("open fifo write ......\n");

	int fd = open(argv[1],O_WRONLY);
	if(fd < 0){
		perror("write fifo error!\n");
		exit(1);
	}else{
		printf("write fifo success: %d\n",fd);
	}

	char *s = "ABCDEFG";
	size_t size = strlen(s);
	if(write(fd,s,size) != size){
		perror("write error!\n");
		exit(1);
	}
	close(fd);

	return 0;
}

与无名管道相同都是阻塞性的读写,适用于socket网络通信。

不同的是打开方式,无名管道通过pipe使用fcntl()系统调用设置O_NOBLOCK设置非阻塞读写。

FIFO通过fcntl()系统调用或者open()设置非阻塞性读写。

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

雲烟

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值