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");
	
}
相关推荐
Tim风声(网络工程师)5 小时前
排查内网互联网访问流程
运维·服务器·网络
坚持就完事了6 小时前
Linux中如何添加环境变量
linux·运维·服务器
l1t7 小时前
mingw和Linux中的gcc和llvm编译器编译的pocketpy执行同一个python脚本的不同效果
linux·运维·python
白緢7 小时前
一、Linux 基础入门
linux·运维·服务器
一袋米扛几楼988 小时前
【网络】网络规划与底层通信:自顶向下方法论 (Top-Down Methodology) 全解析
网络·工程
菜菜艾8 小时前
自动化环境补丁更新系统
linux·运维·bash·运维开发
liulilittle8 小时前
TCP BBR 拥塞控制模块编译
网络·网络协议·tcp/ip
随风,奔跑8 小时前
Nginx
服务器·后端·nginx·web
HalvmånEver8 小时前
MySQL的索引
android·linux·数据库·学习·mysql
仰望星空的打工人9 小时前
cypht无法获取163、126邮件
服务器·网易邮箱大师