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");
	
}
相关推荐
南棱笑笑生2 小时前
20251217给飞凌OK3588-C开发板适配Rockchip原厂的Buildroot【linux-5.10】后调通ov5645【只能预览】
linux·c语言·开发语言·rockchip
科技块儿3 小时前
如何使用IP数据云提升网络风控、减少业务欺诈
网络·网络协议·tcp/ip
fei_sun3 小时前
【计网】2025年真题
网络
Fnetlink13 小时前
中小企业网络环境优化与安全建设
网络·安全·web安全
爬山算法4 小时前
Netty(10)Netty的粘包和拆包问题是什么?如何解决它们?
服务器·网络·tcp/ip
Sleepy MargulisItG4 小时前
【Linux网络编程】应用层协议:HTTP协议
linux·服务器·网络·http
bruce_哈哈哈4 小时前
车载网络--soa总结--some/ip等认识
网络
logic_54 小时前
静态路由配置
运维·服务器·网络
G31135422734 小时前
Linux 内核设计中的核心思想与架构原则
linux·架构·php
zhuzewennamoamtf4 小时前
Linux内核platform抽象、数据结构、内核匹配机制
linux·运维·数据结构