进程间通信--匿名管道

进程间通信介绍

 进程间通信目的

  • 数据传输:一个进程需要将它的数据发送给另一个进程
  • 资源共享:多个进程之间共享同样的资源。
  • 通知事件:一个进程需要向另一个或一组进程发送消息,通知它(它们)发生了某种事件(如进程终止时要通知父进程)。
  • 进程控制:有些进程希望完全控制另一个进程的执行(如Debug进程),此时控制进程希望能够拦截另一个进程的所有陷入和异常,并能够及时知道它的状态改变。

 管道


什么是管道
管道是Unix中最古老的进程间通信的形式。我们把从一个进程连接到另一个进程的一个数据流称为一个“管道”如:

 用fork来共享管道原理

 站在文件描述符角度-深度理解管道 (内存级)

 左边是进程管理,右边是文件管理,进程通过全局变量能找到文件描述符标,也就找到了对应的file文件也能打开磁盘上的文件拷贝到缓冲区里进行读写,父进程创建子进程,发生写实拷贝,类似于浅拷贝,此时不做文件操作,文件描述符里面的对于关系和父进程一样,struc_file没有关闭,因为父进程还在, struc_file的对应的引用计数不为0就一定不会关闭,既然访问的同一个struc_file,也可以同时访问其中的file文件,通过缓冲区可以进行文件的读写

  1. 父进程通过读写两种方式打开内存级的文件返回给上层完成管道的创建
  2. 子进程继承父进程的文件描述符表,发生浅拷贝,也能拿到父进程以读写打开的管道文件
  3. 父子都看得到,让父子单向通信,父进程写,子进程读,各自关闭掉自己不需要的文件描述符

这个是管道是OS单独设计的,得配上单独的系统调用:pipe 内存级的,不需要文件路径,没有文件名,所以叫匿名管道,那我们怎么保证,两个进程打开的是同一个管道的?

子进程继承了父进程的文件描述符表

站在内核角度-管道本质

 匿名管道

#include <unistd.h>
功能:创建⼀⽆名管道
原型
int pipe(int fd[2]);
参数
fd:⽂件描述符数组,其中fd[0]表⽰读端, fd[1]表⽰写端
返回值:成功返回0,失败返回错误代码
#include<iostream>
#include<unistd.h>
using namespace std;
int main()
{int fds[2]={0};int n=pipe(fds);if(n<0){cerr<<"Pipe error"<<endl;return 1;}cout<<"fds[0]"<<fds[0]<<endl;cout<<"fds[1]"<<fds[1]<<endl;return 0;
}

0,1,2被三个标准占用了,从3,4开始

父写子读,实现通信

#include<iostream>
#include<unistd.h>
#include<sys/wait.h>
#include<sys/types.h>
#include<cstring>
using namespace std;void ChildWrite(int fd)
{
char buffer[1024];
int cnt=0;
while(true)
{
snprintf(buffer,sizeof(buffer),"I am child,pid:%d cnt:%d\n",getpid(),cnt++); 
write(fd,buffer,strlen(buffer));
sleep(1);
}
}
void FatherRead(int fd)
{char buffer[1024];while(true){buffer[0]=0;ssize_t n=read(fd,buffer,sizeof(buffer)-1);if(n>0){buffer[n]=0;cout<<"child says: "<<buffer<<endl;}}
}
int main()
{  //1.创建管道int fds[2]={0}; //fds[0]读端,fds[1]写端int n=pipe(fds);if(n<0){cerr<<"Pipe error"<<endl;return 1;}cout<<"fds[0]"<<fds[0]<<endl;cout<<"fds[1]"<<fds[1]<<endl;//3.创建子进程 f->r c->wpid_t id=fork();if(id==0){//childclose(fds[0]); //关闭读端ChildWrite(fds[1]);close(fds[1]);exit(0);}
close(fds[1]); //关闭写端
FatherRead(fds[0]);
waitpid(id,nullptr,0);
close(fds[0]);return 0;
}

父进程写的cnt在不断变化,子进程能读到,说明实现了管道通信

五种特性

1.匿名管道,只能用来进行具有血缘关系的进程进行进程间通信(常用父与子,如上述代码)

2.管道文件,自带同步机制(父子进程进行IO同时进行,一个读一个写,不管是父快还是子快,父不断写,子read读不到会阻塞住直到读到为止)

3.管道是面向字节流的

4.管道是单向通信的(要么父写子读,要么子写父读)

5. (管道)文件的生命周期随进程

4种通信情况 

1.写慢,读快------>读端阻塞等待写端(进程)

2.写快,读慢------>缓冲区写满了,写要阻塞等待读端

3.写关,读开------>read会读到返回值0,表示文件结尾

//写一条就关
void ChildWrite(int fd)
{
char buffer[1024];
int cnt=0;
while(true)
{
snprintf(buffer,sizeof(buffer),"I am child,pid:%d cnt:%d\n",getpid(),cnt++); 
write(fd,buffer,strlen(buffer));
sleep(1);
break;
}
}
//观察n的返回值
void FatherRead(int fd)
{char buffer[1024];while(true){buffer[0]=0;ssize_t n=read(fd,buffer,sizeof(buffer)-1);if(n>0){buffer[n]=0;cout<<"child says: "<<buffer<<endl;}else{cout<< "n:"<<n<<endl;}}
}

 4.读关,写开------->写端再写没有意义,OS会杀掉写端进程

#include<iostream>
#include<unistd.h>
#include<sys/wait.h>
#include<sys/types.h>
#include<cstring>
using namespace std;void ChildWrite(int fd)
{
char buffer[1024];
int cnt=0;
while(true)
{
snprintf(buffer,sizeof(buffer),"I am child,pid:%d cnt:%d\n",getpid(),cnt++); 
write(fd,buffer,strlen(buffer));
sleep(1);
}
}
void FatherRead(int fd)
{char buffer[1024];while(true){buffer[0]=0;ssize_t n=read(fd,buffer,sizeof(buffer)-1);if(n>0){buffer[n]=0;cout<<"child says: "<<buffer<<endl;}else{cout<< "n:"<<n<<endl;sleep(4);}break;}
}
int main()
{  //1.创建管道int fds[2]={0}; //fds[0]读端,fds[1]写端int n=pipe(fds);if(n<0){cerr<<"Pipe error"<<endl;return 1;} cout<<"fds[0]"<<fds[0]<<endl;cout<<"fds[1]"<<fds[1]<<endl;//3.创建子进程 f->r c->wpid_t id=fork();if(id==0){//childclose(fds[0]); //关闭读端ChildWrite(fds[1]);close(fds[1]);exit(0);}
close(fds[1]); //关闭写端
FatherRead(fds[0]);
close(fds[0]);int status;
int ret=waitpid(id,&status,0);
//获取到子进程的退出状态
if(ret>0)
{printf("child code: %d exited  status: %d\n",(status)>>8&0xff,(status)&0x7f);
}
return 0;
}

发送异常信号13 SIGPIPE 

 基于匿名管道----进程池

父进程创建多个子进程,用匿名管道分派任务

 1.构建进程链,为进程池做准备

#ifndef __PROCESS__POOL_HPP__
#define __PROCESS__POOL_HPP__
#include <iostream>
#include <vector>
#include <unistd.h>
#include<cstdlib>
using namespace std;
const int gdefaultnum = 5; // 要创建几个进程
// 先描述 单个进程
class Channel
{
public:Channel() {}~Channel() {}private:int _wfd;
};// 在组织  进程链
class ChannelManager
{
public:ChannelManager() {}~ChannelManager() {}private:vector<Channel> _channels;
};

 2.创建进程池,提供管道条件

// 进程池
class ProcessPool
{
public:ProcessPool(int num) : _process_num(num) {}~ProcessPool() {}bool Create(){int pipefd[2] = {0};for (int i = 0; i < _process_num; i++){// 1.创建管道int n = pipe(pipefd);if (n < 0)return false;}// 2.创建子进程  各自关闭不需要的文件描述符pid_t id = fork();if (id < 0)return false;else if (id == 0){// 子进程 --->读// 3.关闭不需要的文件描述符close(pipefd[1]);exit(0);}else{// 父进程 --->写// 3.关闭不需要的文件描述符close(pipefd[0]);}return true;}private:ChannelManager _cm; // 进程链int _process_num;   // 进程个数
};

3.父子各自打印验证是否通信

void BuildChannel(int wfd, pid_t subid){_channels.emplace_back(wfd, subid);// Channel c(wfd,subid);// _channels.push_back(c);}void Print()
{for(auto  &chnnel : _channels){
cout<<chnnel.Name()<<endl;}
}void Work(int rfd){while (true){cout << "我是子进程,我的rfd是:" << rfd << endl;sleep(2);}}
//ProcessPool.hpp
#ifndef __PROCESS__POOL_HPP__
#define __PROCESS__POOL_HPP__
#include <iostream>
#include <vector>
#include <unistd.h>
#include <cstdlib>
using namespace std;
const int gdefaultnum = 5; // 要创建几个进程
// 先描述 单个进程
class Channel
{
public:Channel(int fd, pid_t id) : _wfd(fd), _subid(id) { _name = "chnnel-" + std::to_string(_wfd) + "-" + std::to_string(_subid); }~Channel() {}int Fd(){return  _wfd;}pid_t Subid(){return  _subid;}string Name(){return  _name;}
private:int _wfd;pid_t _subid;std::string _name;
};// 在组织  进程链
class ChannelManager
{
public:ChannelManager() {}~ChannelManager() {}void BuildChannel(int wfd, pid_t subid){_channels.emplace_back(wfd, subid);// Channel c(wfd,subid);// _channels.push_back(c);}void Print()
{for(auto  &chnnel : _channels){
cout<<chnnel.Name()<<endl;}
}
private:vector<Channel> _channels;
};// 进程池
class ProcessPool
{
public:ProcessPool(int num) : _process_num(num) {}~ProcessPool() {}void Work(int rfd){while (true){cout << "我是子进程,我的rfd是:" << rfd << endl;sleep(2);}}bool Create(){for (int i = 0; i < _process_num; i++){int pipefd[2] = {0};// 1.创建管道int n = pipe(pipefd);if (n < 0)return false;// 2.创建子进程  父子各自关闭不需要的文件描述符pid_t id = fork();if (id < 0)return false;else if (id == 0){// 子进程 --->读// 3.关闭不需要的文件描述符close(pipefd[1]);Work(pipefd[0]);exit(0);}else{// 父进程 --->写// 3.关闭不需要的文件描述符close(pipefd[0]);_cm.BuildChannel(pipefd[1], id);close(pipefd[1]);}}return true;}void Debug(){_cm.Print();}
private:ChannelManager _cm; // 进程链int _process_num;   // 进程个数
};#endif
//Main.cc#include"ProcessPool.hpp"int main()
{ProcessPool pp(gdefaultnum);//创建进程池pp.Create();//打印进程池pp.Debug();sleep(1000);return 0;
}

实现通信 

 4.分配任务,子写父读

 void Work(int rfd){while (true){int code = 0;ssize_t n = read(rfd, &code, sizeof(code));if (n > 0){if (n == sizeof(code)){continue;}cout << "子进程[]"<<getpid()<<"]收到一个任务码:" << code << endl;}else if (n == 0){cout << "子进程退出" << endl;break;}else{// 读失败cout << "读取错误" << endl;break;}}}void PushTack(int taskcode){// 1.选择一个子进程,采用轮询,防止负载均衡和负载不均衡auto &c = _cm.Select();cout << "选择一个子进程:" << c.Name() << endl;// 2.发送任务c.Send(taskcode);cout << "发送了一个任务码:" << taskcode << endl;}

完整代码

//ProcessPool.hpp
#ifndef __PROCESS__POOL_HPP__
#define __PROCESS__POOL_HPP__
#include <iostream>
#include <vector>
#include <unistd.h>
#include <cstdlib>
using namespace std;
const int gdefaultnum = 5; // 要创建几个进程
// 先描述 单个进程
class Channel
{
public:Channel(int fd, pid_t id) : _wfd(fd), _subid(id) { _name = "chnnel-" + std::to_string(_wfd) + "-" + std::to_string(_subid); }~Channel() {}int Fd() { return _wfd; }pid_t Subid() { return _subid; }string Name() { return _name; }void Send(int code){int n = write(_wfd, &code, sizeof(code));(void)n;}private:int _wfd;pid_t _subid;std::string _name;
};// 在组织  进程链
class ChannelManager
{
public:ChannelManager() : _next(0) {}~ChannelManager() {}void BuildChannel(int wfd, pid_t subid){_channels.emplace_back(wfd, subid);// Channel c(wfd,subid);// _channels.push_back(c);}// 轮询Channel &Select(){auto &c = _channels[_next];_next++;_next %= _channels.size();return c;}void Print(){for (auto &chnnel : _channels){cout << chnnel.Name() << endl;}}private:vector<Channel> _channels;int _next;
};// 进程池
class ProcessPool
{
public:ProcessPool(int num) : _process_num(num) {}~ProcessPool() {}void Work(int rfd){while (true){int code = 0;ssize_t n = read(rfd, &code, sizeof(code));if (n > 0){if (n == sizeof(code)){continue;}cout << "子进程[]"<<getpid()<<"]收到一个任务码:" << code << endl;}else if (n == 0){cout << "子进程退出" << endl;break;}else{// 读失败cout << "读取错误" << endl;break;}}}bool Create(){for (int i = 0; i < _process_num; i++){int pipefd[2] = {0};// 1.创建管道int n = pipe(pipefd);if (n < 0)return false;// 2.创建子进程  父子各自关闭不需要的文件描述符pid_t id = fork();if (id < 0)return false;else if (id == 0){// 子进程 --->读// 3.关闭不需要的文件描述符close(pipefd[1]);Work(pipefd[0]);exit(0);}else{// 父进程 --->写// 3.关闭不需要的文件描述符close(pipefd[0]);_cm.BuildChannel(pipefd[1], id);close(pipefd[1]);}}return true;}void Debug(){_cm.Print();}void PushTack(int taskcode){// 1.选择一个子进程,采用轮询,防止负载均衡和负载不均衡auto &c = _cm.Select();cout << "选择一个子进程:" << c.Name() << endl;// 2.发送任务c.Send(taskcode);cout << "发送了一个任务码:" << taskcode << endl;}private:ChannelManager _cm; // 进程链int _process_num;   // 进程个数
};#endif
//Main.cc#include"ProcessPool.hpp"int main()
{ProcessPool pp(gdefaultnum);//创建进程池pp.Create();//打印进程池//pp.Debug();int task_code = 1;while(true){pp.PushTack(task_code++);sleep(1);}return 0;
}

创建进程池后,OS关闭了没有意义的管道,每次选择一个管道接受消息 

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.rhkb.cn/news/34655.html

如若内容造成侵权/违法违规/事实不符,请联系长河编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

【鸿蒙开发】Hi3861学习笔记-Visual Studio Code安装(New)

00. 目录 文章目录 00. 目录01. Visual Studio Code概述02. Visual Studio Code下载03. Visual Studio Code安装04. Visual Studio Code插件05. 附录 01. Visual Studio Code概述 vscode是一种简化且高效的代码编辑器&#xff0c;同时支持诸如调试&#xff0c;任务执行和版本管…

人工智能 Day06 pandas库进阶

1.处理缺失数据 总体流程是这样的&#xff0c; 归根在于如何处理NAN&#xff0c;接下来详细赘述 1.1. 处理缺失值的相关函数 判断缺失值 pd.isnull(df)&#xff1a;用于判断 DataFrame df 中的元素是否为缺失值&#xff08;NaN &#xff09;&#xff0c;返回一个与df 形状相同…

【Tools】Visual Studio Code安装保姆级教程(2025版)

00. 目录 文章目录 00. 目录01. Visual Studio Code概述02. Visual Studio Code下载03. Visual Studio Code安装04. Visual Studio Code配置05. 附录 01. Visual Studio Code概述 Visual Studio Code&#xff08;简称 VS Code&#xff09;是由微软开发的一款免费、开源且跨平台…

14.使用各种读写包操作 Excel 文件:辅助模块

一 各种读写包 这些是 pandas 在底层使用的各种读写包。无须安装 pandas&#xff0c;直接使用这些读写包就能够读写 Excel 工作簿。可以尽可能地使用 pandas 来解决这类问题&#xff0c;只在 pandas 没有提供你所需要的功能时才用到读写包。 表中没有 xlwings &#xff0c;因为…

AI赋能实时安全背带监测解决方案

背景&#xff1a;安全背带检测的行业刚需与技术痛点 在建筑施工、石油化工、仓储物流等高危行业中&#xff0c;安全背带是保障作业人员生命安全的最后一道防线。据统计&#xff0c;超过30%的高空坠落事故与未正确佩戴安全背带直接相关。传统依赖人工巡检的监督方式存在效率低、…

神聖的綫性代數速成例題2. 行列式的性質

性質 1&#xff1a;行列式與它的轉置行列式相等&#xff1a; 設為行列式&#xff0c;為其轉置行列式&#xff0c;則。 性質 2&#xff1a;交換行列式的兩行 (列)&#xff0c;行列式變號&#xff1a; 若行列式經過交換第行和第行得到行列式&#xff0c;則。 性質 3&#xff…

大模型推理 memory bandwidth bound (3) - MLA

系列文章目录 大模型推理 & memory bandwidth bound (1) - 性能瓶颈与优化概述 大模型推理 & memory bandwidth bound (2) - Multi-Query Attention 大模型推理 & memory bandwidth bound (3) - MLA 文章目录 系列文章目录前言一、原理1.低秩压缩 & 动机2.矩阵…

CTP开发爬坑指北(九)

CTP API开发中有很多需要注意的小细节&#xff0c;稍有不慎就会出问题&#xff0c;不然&#xff0c;轻则表现与预期不符&#xff0c;重则程序崩溃影响策略盈利。本系列将容易遇到的坑列出来&#xff0c;以供开发时参考&#xff0c;如有疑义之处&#xff0c;欢迎指正。 在国内期…

python_巨潮年报pdf下载

目录 前置&#xff1a; 步骤&#xff1a; step one: pip安装必要包&#xff0c;获取年报url列表 step two: 将查看url列表转换为pdf url step three: 多进程下载pdf 前置&#xff1a; 1 了解一些股票的基本面需要看历年年报&#xff0c;在巨潮一个个下载比较费时间&…

量化交易backtrader实践(五)_策略综合篇(3)_经典策略复盘

01_经典策略复盘 在某款股票软件手机版App上&#xff0c;有一项“复盘”的功能&#xff0c;这个功能很强大&#xff0c;它能把这支股票近1年的走势&#xff0c;用设置好的六个策略去回测&#xff0c;得到每个策略的近一年的收益率&#xff0c;并做了从最好到最差的排序。这就能…

蓝桥与力扣刷题(蓝桥 字符统计)

题目&#xff1a;给定一个只包含大写字母的字符出 S, 请你输出其中出现次数最多的字符。如果有多个字母均出现了最多次, 按字母表顺序依次输出所有这些字母。 输入格式 一个只包含大写字母的字等串 S. 输出格式 若干个大写字母&#xff0c;代表答案。 样例输入 BABBACAC样…

protobuf安装

安装 github官方链接 https://github.com/protocolbuffers/protobuf/ 以protobuf21为例 https://github.com/protocolbuffers/protobuf/releases/download/v21.11/protobuf-all-21.11.zip windows 解压好文件夹后,使用cmake,vs,qt creator等工具打开该项目,进行编译,编译需…

Compose 实践与探索八 —— LayoutModifier 解析

前面几节讲的 Modifier 都是起辅助作用的&#xff0c;比如 Modifier 的伴生对象、CombinedModifier、 ComposedModifier 以及几乎所有 Modifier 的父接口 Modifier.Element。本篇我们开始讲具有直接功效的 Modifier&#xff0c;分为几个大类&#xff1a;LayoutModifier、DrawMo…

stl之string的详解

一&#xff0c;string定义的方式 &#xff0c;string定义了多种函数重载的方式&#xff0c;常用的构造函数如下&#xff1a; string(); string(const string& str); string(const string& str, size_t pos, size_t len npos); string(const char* s); string(const …

Leetcode-131.Palindrome Partitioning [C++][Java]

目录 一、题目描述 二、解题思路 【C】 【Java】 Leetcode-131.Palindrome Partitioninghttps://leetcode.com/problems/palindrome-partitioning/description/131. 分割回文串 - 力扣&#xff08;LeetCode&#xff09;131. 分割回文串 - 给你一个字符串 s&#xff0c;请你…

InternVL:论文阅读 -- 多模态大模型(视觉语言模型)

更多内容&#xff1a;XiaoJ的知识星球 文章目录 InternVL: 扩展视觉基础模型与通用视觉语言任务对齐1.概述2.InternVL整体架构1&#xff09;大型视觉编码器&#xff1a;InternViT-6B2&#xff09;语言中间件&#xff1a;QLLaMA。3&#xff09;训练策略&#xff08;1&#xff09…

【AWS入门】AWS云计算简介

【AWS入门】AWS云计算简介 A Brief Introduction to AWS Cloud Computing By JacksonML 什么是云计算&#xff1f;云计算能干什么&#xff1f;我们如何利用云计算&#xff1f;云计算如何实现&#xff1f; 带着一系列问题&#xff0c;我将做一个普通布道者&#xff0c;引领广…

二分算法刷题

1. 初识 总结&#xff1a;二分算法题的细节非常多&#xff0c;容易写出死循环。使用算法的条件不一定是数组有序&#xff0c;而是具有“二断性”&#xff1b;模板三种后面会讲。 朴素二分二分查找左端点二分查找右端点 2. 朴素二分 题目链接&#xff1a;704. 二分查找 - 力扣…

itsdangerous加解密源码分析|BUG汇总

这是我这两天的思考 早知道密码学的课就不旷那么多了 纯个人见解 如需转载&#xff0c;标记出处 目录 一、官网介绍 二、事例代码 源码分析&#xff1a; 加密函数dump源码使用的函数如下&#xff1a; 解密 ​编辑 ​编辑 关于签名&#xff1a; 为什么这个数字签名没有…

深度解析React Native底层核心架构

React Native 工作原理深度解析 一、核心架构&#xff1a;三层异构协作体系 React Native 的跨平台能力源于其独特的 JS层-Shadow层-Native层 架构设计&#xff0c;三者在不同线程中协同工作&#xff1a; JS层 运行于JavaScriptCore&#xff08;iOS&#xff09;或Hermes&…