Linux之管道

管道

管道

什么是管道

管道是Linux中最古老的进程间通信的方式

我们把一个进程连接到另一个进程的一个数据流称作 一个管道
注意:管道只能单向通信
你可以把他看做是一种特殊的文件,也能够进行,read,open等操作,但是他不属于任何文件系统,他只存在于内存之中

匿名管道

匿名管道,没有名字

父子进程之间,直接使用文件描述符号
1.创建描述符号,2个

int fds[2];

fds[0]用来读

ds[1]用来写
2.把文件描述符号变成管道

pipe
3.使用管道进行通信
4.关闭

read

读文件

头文件是 unistd.h

注意: 这里三个参数,第一个fd(管道,文件),第二个数组,第三个读取的大小

pipe

将int类型的数组 转换成管道 (创建管道)

头文件,仍然是unistd

write,将文件的内容写出来

第一个参数是fd(管道),第二个参数是(void *)类型的指针,第三个参数是指写的大小

应用

父进程读取数据,子进程写数据

cpp 复制代码
#include<stdio.h>
#include<unistd.h>
#include<string.h>

int main()
{
	int fd[2];
	pipe(fd);

	if(fork())
	{
		char temp[1024];
		int r;

		while(1)
		{
			r = read(fd[0], temp, 1023);
			if(r > 0)
			{
				temp[r] = 0; // /0 结束
				printf(">> %s\n", temp);
			}
		}
	
	}
	else
	{
		char temp[1024];
		while(1)
		{
			memset(temp, 0, 1024);
			printf("you want to send ?");

			scanf("%s",temp);

			write(fd[1], temp, strlen(temp));
		}
	}

	close(fd[0]);
	close(fd[1]);

	return 0;
}

有名管道

有名字
> 可以在同一主机上不同进程之间操作, 用具体的文件
1.创建管道文件(mkfifo)

2.打开管道文件(open)

3.使用

4.关闭(close)

5.删除管道文件(unlink)

mkfifo

mkfifo,这个是用来创建有名管道的函数

返回值是int类型的

包含两个头文件

sys/types.h 以及 sys/stat.h
第一个参数是写文件的名称,第二个参数是写这个文件的权限
如果创建成功,返回0,创建失败返回-1

open

打开文件

头文件包括 sys/types.h, sys/stat.h. fcntl.h

第一个参数是文件名称,第二个参数打开方式
文件打开方式 常用选项是:O_RDONLY(只读);O_WRONLY(只写); O_RDWR(可读写); O_CREAT:
文件不存在时,创建该文件, 文件的权限由第三个参数mode决定最终的权限
注意:打开失败的话,返回-1,打开成功返回int

unlink ,系统调用函数,用来删除指定文件

头文件还是unistd.h

参数是文件名称

copy on write

写时拷贝,只有当你写的时候才拷贝,当你读的是时候不拷贝
案例

cpp 复制代码
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <fcntl.h>
#include <stdlib.h>

int main(){
	//1 创建管道文件(mkfifo)
	int r = mkfifo("test.pipe",0666);
	if(0 == r) printf("创建管道文件:%m\n");
	else printf("创建管道文件失败:%m\n"),exit(-1);
	//2 打开管道文件						
	int fd = open("test.pipe",O_WRONLY);
	if(-1 == fd) printf("打开管道文件失败:%m\n"),unlink("test.pipe"),exit(-1);
	printf("打开管道文件成功!\n");
	//3 使用管道文件 写	 
	int n = 0;
	char buff[56];
	while(1){
		memset(buff,0,56);
		sprintf(buff,"温柔了岁月:%d",++n);
		write(fd,buff,strlen(buff));
		sleep(1);
	}
	//4 关闭 	
	close(fd);						
	//5 删除管道文件
	unlink("test.pipe");
	
}
相关推荐
惜.己19 分钟前
Linux常用命令(十四)
linux·运维·服务器
linkingvision1 小时前
H5S 视频监控AWS S3 对象存储
linux·运维·aws·视频监控s3对象存储
BillKu1 小时前
服务器多JAR程序运行与管理指南
运维·服务器·jar
QQ2740287562 小时前
BlockMesh Ai项目 监控节点部署教程
运维·服务器·web3
belldeep2 小时前
WSL 安装 Debian 12 后,Linux 如何安装 vim ?
linux·debian·vim
wqqqianqian2 小时前
国产linux系统(银河麒麟,统信uos)使用 PageOffice自定义Word模版中的数据区域
linux·word·自定义·pageoffice·数据区域
小疆智控3 小时前
数字化工厂升级引擎:Modbus TCP转Profinet网关助力打造柔性生产系统
服务器·网络·tcp/ip
南棱笑笑生3 小时前
20250512给NanoPi NEO core开发板在Ubuntu core20.04系统更新boot.img
linux·运维·ubuntu
XMYX-03 小时前
Linux du 命令终极指南:从基础到精通
linux·服务器
DourPanda3 小时前
polarctf-web-[rce1]
linux·网络协议·网络安全