命名(有名)管道的使用 学习笔记

目录

一、特点:

二、使用步骤:

三、源代码:

1.read:

2.write:


一、特点:

- 有文件名,可以使用open函数打开
- 任意进程间数据传输
- write和read操作可能会阻塞进程
- write具有"原子性"
    原子性简单来说可以理解为,当命名管道剩余的空间不足以将数据全部写入时,就不执行。


二、使用步骤:

- 第一个进程mkfifo有名管道
- open有名管道,write/read数据
- close有名管道
- 第二个进程open有名管道,read/write数据
- close有名管道


三、源代码:

1.read:

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <limits.h>
#include <stdlib.h>

//有名管道的文件名
#define MYFIFO "/tmp/myfifo"


/*有名管道具有原子性,不同系统下fifo的长度是不一样的,
在limits.h头文件中定义了不同操作系统下fifo长度的定义(PIPE_BUF)
所以需要包含该头文件来定义fifo的长度*/
#define MAX_BUFFER_SIZE PIPE_BUF

int main(int argc,char *argv[])
{
	pid_t fd;
	int fifo_read_byte;
	char fifo_read[MAX_BUFFER_SIZE] = {0};

	//判断有名管道是否已经存在,若不存在则以相应的权限创建
	if(access(MYFIFO,F_OK) == -1)
	{
		if(mkfifo(MYFIFO,0666) < 0)
		{
			printf("fifo erro!\r\n");
			exit(1);
		}
	}
	//以只读的方式打开有名管道
	fd = open(MYFIFO,O_RDONLY);

	if(fd == -1)//如果打开失败则退出并打印失败信息
	{
		printf("open error!\r\n");
		exit(2);
	}

	while(1)
	{	
		memset(fifo_read,0,sizeof(fifo_read));//读取之前先将接收数据的数组清空
		
		fifo_read_byte = read(fd,fifo_read,MAX_BUFFER_SIZE);//从有名管道读取数据

		if (fifo_read_byte > 0)/*如果从fifo读取到数据则打印并且退出*/
		{
			printf("'%d' byte read from fifo '%s' \r\n",fifo_read_byte,fifo_read);
			
			close(fd);

			remove(MYFIFO);//删除fifo

			exit(0);
		}
	}
}

2.write:

#include <stdio.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <limits.h>
#include <stdlib.h>

#define MYFIFO "/tmp/myfifo"

#define MAX_BUFFER_SIZE PIPE_BUF

int main(int argc,char *argv[])
{
	pid_t fd;
	char fifo_write[MAX_BUFFER_SIZE] = {0};
	int fifo_write_byte;

	//判断有名管道是否已经存在,若不存在则以相应的权限创建
	if(access(MYFIFO,F_OK) == -1)
	{
		if(mkfifo(MYFIFO,0666) < 0)
		{
			printf("fifo erro!\r\n");
			exit(1);
		}
	}

	//如果没有发送数据那么退出并打印相关信息,argc的值默认+1
	if(argc <= 1)
	{
		printf("please input string!\r\n");
		exit(1);
	}
	//将控制台中的第一个数据填充到接收数组
	sscanf(argv[1],"%s",fifo_write);
	
	//以只写的方式打开有名管道
	fd = open(MYFIFO,O_WRONLY);

	//如果打开失败则退出
	if(fd == -1)
	{
		printf("open error!\r\n");
		exit(1);
	}

	//将fifo_write中的数据从fifo发送出去
	fifo_write_byte = write(fd,fifo_write,MAX_BUFFER_SIZE);

	//将发送的数据打印出来
	if(fifo_write_byte > 0)
	{
		printf("'%d' byte write from fifo '%s' \r\n",fifo_write_byte,fifo_write);
	}

	close(fd);

	exit(0);
	
}
  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值