Linux之管道

管道

管道

什么是管道

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

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

匿名管道

匿名管道,没有名字

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

int fds2;

fds0用来读

ds1用来写
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");
	
}
相关推荐
PiaoKe___1 小时前
云手机原理与 Python 自动化实战:ADB 批量控制、任务调度与落地建议
服务器·arm开发·python·自动化
en.en..4 小时前
Linux 七大文件类型 详解
网络
NamoAmitabha1287 小时前
libpng12-0 1.2.54-1ubuntu1.1 (amd64 binary) in ubuntu xenial
linux·ubuntu20.4
IPdodo_7 小时前
跨境 API 调用不稳定怎么办:出口、超时重试与链路监控的实践
网络·python·网络协议
Madison-No78 小时前
搭建项目测试环境
linux·运维·服务器·python
吴声子夜歌9 小时前
Shell编程实例——编写安全的shell脚本(二)
linux·运维·shell
悠悠121389 小时前
微服务通信别只看性能:REST 与 gRPC 的 6 个选型判断和一次 502 故障复盘
运维·服务器
xiaoye-duck10 小时前
《Linux 网络编程》深入理解 IP 协议(二):网段划分、私有 IP 与 NAT 地址转换
linux·网络·ip
云老大-阿里云国际站代理商11 小时前
华为云国际站服务代理商:NAT网关怎么配?多台ECS共用公网IP要注意什么
服务器·华为云·云计算
zx_7414848111 小时前
【Linux入门】Shell 函数、正则表达式与文本处理:cut 与 awk
linux·运维·正则表达式