【Linux基础(四)】管道

本文详细介绍了C++中管道的概念、分类(匿名管道和命名管道)、特点,以及如何使用pipe函数、access函数、mkfifo函数创建和操作匿名管道与命名FIFO文件。还给出了写入和读取操作的示例,以及删除FIFO文件的方法。
摘要由CSDN通过智能技术生成

1、什么是管道

在这里插入图片描述
管道可以传输各种类型数据,因为write函数的参数是void*类型。
管道最大容纳65535字节=64kb
在这里插入图片描述

2、管道的分类

1、匿名管道:只能使用在具有亲缘关系(父子进程、兄弟进程)的进程之间
2、命名管道:不限于任何关系之间

3、管道的特点

1、读入写出,确定方向,使用close()关闭其中一个描述符。
2、管道一旦建立好,则是单行道,不能修改方向,只能在开一个管道。
在这里插入图片描述

在这里插入图片描述

4、pipe函数(匿名管道)

在这里插入图片描述

#include <iostream>
#include <unistd.h>
#include <stdio.h>
using namespace std;
typedef struct student
{
	char stuName[20];
	char stuNum[10];
	int  age;
}STU;

int main()
{
	char buf[20]={0}int fdarr[2]={0};
	int res=pipe(fdarr);
	if(res!=0)
	{
		perror("pipe error);
	}
	else
	{
		pid_t pid = fork();
		//父进程发  子进程收
		if(pid>0)
		{
			STU stu ={"张三","1001",19};
			cout<<"父进程 pid ="<<getpid()<<endl;
			close(fdarr[0]);//关闭父进程读
			while(1)
			{
				//cin>>buf;
				//write(fdarr[1],buf,sizeof(buf));
				
				write(fdarr[1],&stu,sizeof(STU));
				sleep(10);
			}
			
		}
		else if(pid ==0 )
		{
			STU resStu;
			cout<<"子进程pid = "<<getpid()<<endl;
			close(fdarr[1]);//关闭子进程写
			while(1)
			{
				//read(fdarr[0],buf,sizeof(buf));
				//cout<<"pid = "<<getpid()<<"buf="<<buf<<endl;
				read(fdarr[0],&resStu,sizeof(STU));//阻塞函数
				cout<<"resStu.stdName"<<resStu.stuName<<endl;
			}
		}	
	}
	return 0;
}

5、命名管道:FIFO文件

在这里插入图片描述

5.1、创建一个命名管道

在这里插入图片描述

5.2、访问一个FIFO文件

在这里插入图片描述

6、命名管道示例

6.1、写操作示例

#include <iostream>
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
using namespace std;

int main()
{
	int wfd =0;
	umask(0);
	if(access("/root/project/AtoB.fifo",F_OK)==-1)//访问路径是否存在
	{
		if(mkfifo("/root/projects/AtoB.fifo",0777)==-1)
		{
			perror("mkfifo error");
		}
		else
		{
			cout<<"文件创建成功"<<endl;
		}
	}else
	{
		cout<<"文件已经存在"<<endl;
	}
	wfd = open("/root/project/AtoB.fifo",O_WRONLY);
	char buf[20] ={0};
	while(1)
	{
		cin>>buf;
		write(wfd,buf,sizeof(buf));
	}
	return 0;
}

6.2、读操作示例

#include <iostream>
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
using namespace std;

int main()
{
	int rfd =0;
	umask(0);
	if(access("/root/project/AtoB.fifo",F_OK)==-1)//访问路径是否存在
	{
		if(mkfifo("/root/projects/AtoB.fifo",0777)==-1)
		{
			perror("mkfifo error");
		}
		else
		{
			cout<<"文件创建成功"<<endl;
		}
	}else
	{
		cout<<"文件已经存在"<<endl;
	}
	rfd = open("/root/project/AtoB.fifo",O_RDONLY);
	char buf[20] ={0};
	while(1)
	{
		read(rfd,buf,sizeof(buf));
		cout<<"buf ="<<buf<<endl;
		bzero(buf,sizeof(buf));
	}
	
	return 0;
}

7、access函数和mkfifo函数

在这里插入图片描述
在这里插入图片描述

8、删除FIFO文件

在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值