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");
	
}
相关推荐
IC 见路不走12 分钟前
LeetCode 第91题:解码方法
linux·运维·服务器
翻滚吧键盘25 分钟前
查看linux中steam游戏的兼容性
linux·运维·游戏
小能喵29 分钟前
Kali Linux Wifi 伪造热点
linux·安全·kali·kali linux
汀沿河43 分钟前
8.1 prefix Tunning与Prompt Tunning模型微调方法
linux·运维·服务器·人工智能
zly35001 小时前
centos7 ping127.0.0.1不通
linux·运维·服务器
小哥山水之间2 小时前
基于dropbear实现嵌入式系统ssh服务端与客户端完整交互
linux
power 雀儿2 小时前
集群聊天服务器---MySQL数据库的建立
服务器·数据库·mysql
ldj20202 小时前
2025 Centos 安装PostgreSQL
linux·postgresql·centos
翻滚吧键盘2 小时前
opensuse tumbleweed上安装显卡驱动
linux
Bruce_Liuxiaowei2 小时前
常见高危端口风险分析与防护指南
网络·网络安全·端口·信息搜集