有名管道通讯编程

1. 核心理论

有名管道又称为 FIFO文件,因此我们对有名管道的操作可以采用操作文件的方式,如使用open,write,read等。
有名管道可以用于任意进程间通信。

FIFO文件对比普通文件
1. 读取Fifo文件的进程只能以“RDONLY”方式打开。
2. 写Fifo文件的进程只能以“WRONLY”方式打开。
3. Fifo文件里面的内容被读取后,就消失了,但是普通文件的内容被读取后还存在

2.函数学习

创建有名管道
函数名:mkfifo
函数原型:int mkfifo(const char *pathname,mode_t mode);
函数功能:创建一个FIFO文件
头文件: <sys/types.h>  <sys/stat.h>
返回值: 成功:0  失败:-1
参数说明: pathname:要创建的带路径的文件名     mode:文件的访问权限

删除有名管道
函数名:unlink
函数原型:int unlink(const char *pathname);
函数功能: 删除文件(包括fifo文件)
头文件: <unistd.h>
返回值:成功:0   失败:-1
参数说明:pathname:指明要删除的文件名(带路径)

3. 综合实例

任意两个进程利用有名管道通讯
/*fifo_write.c*/

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>

void main()
{
	int fd;
	
	/*创建fifo文件*/
	mkfifo("/tmp/myfifo",666);
	
	/*打开fifo文件*/
	fd = open("/tmp/myfifo",O_WRONLY);
	
	/*写入数据到fifo文件*/
	write(fd,"hello fifo",11);
	
	close(fd);
}
/*fifo_read.c*/

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>

void main()
{
	int fd;
	char c_buff[15];
	
	fd = open("/tmp/myfifo",O_RDONLY);
	read(fd,c_buff,11);
	printf("read %s\n", c_buff);
	close(fd);
	unlink("/tmp/myfifo");
}
gcc fifo_write.c -o fifo_write
gcc fifo_read.c -o fifo_read

./fifo_write 此时写进程处于阻塞状态
./fifo_read 此时读取到数据,写进程也结束了

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值