💁♂️个人主页:进击的荆棘
👇作者其它专栏:
目录
1.进程间通信介绍
2.管道
3.匿名管道
4.命名管道
5.system V共享内存
6.system V消息队列
7.system V信息量
8.内核是如何组织管理IPC资源的
1.进程间通信介绍
1.1进程间通信的目的
●数据传输:一个进程需要将它的数据发送给另一个进程
●资源共享:多个进程间共享同样的资源
●通知事件:一个进程需要向另一个或一组进程发送消息,通知它(它们)发生了某种事件(如进程终止时要通知父进程)
●进程控制:有些进程希望完全控制另一个进程的执行(如Debug进程),此时控制进程希望能够拦截另一个进程的所有陷入和异常,并能够及时知道它的状态改变
1.2进程间通信发展
●管道
●System V进程间通信
●POSIX进程间通信
1.3进程间通信分类
管道
●匿名管道pipe
●命名管道
System V IPC
●System V 消息队列
●System V 共享内存
●System V信号量
POSIX IPC
●消息队列
●共享内存
●信号量
●互斥量
●条件变量
●读写锁
2.管道
什么是管道
●管道是Unix中最古老的进程间通信的形式
●我们把从一个进程连接到另一个进程的一个数据流称为一个“管道”
3.匿名管道
1#include <unistd.h> 2功能:创建⼀⽆名管道 3原型 4int pipe(int fd[2]); 5参数 6fd:⽂件描述符数组,其中fd[0]表⽰读端, fd[1]表⽰写端 7返回值:成功返回0,失败返回错误代码 8

3.1代码实例
1例⼦:从键盘读取数据,写⼊管道,读取管道,写到屏幕 2#include <stdio.h> 3#include <stdlib.h> 4#include <string.h> 5#include <unistd.h> 6 7int main( void ) 8{ 9 int fds[2]; 10 char buf[100]; 11 int len; 12 if ( pipe(fds) == -1 ) 13 perror("make pipe"),exit(1); 14 // read from stdin 15 while ( fgets(buf, 100, stdin) ) { 16 len = strlen(buf); 17 // write into pipe 18 if ( write(fds[1], buf, len) != len ) { 19 perror("write to pipe"); 20 break; 21 } 22 memset(buf, 0x00, sizeof(buf)); 23 // read from pipe 24 if ( (len=read(fds[0], buf, 100)) == -1 ) { 25 perror("read from pipe"); 26 break; 27 } 28 // write to stdout 29 if ( write(1, buf, len) != len ) { 30 perror("write to stdout"); 31 break; 32 } 33 } 34} 35
3.2用fork来共享管道原理

3.3从文件描述符角度-理解管道

3.4从内核角度-管道本质

所以,可以把管道看成文件,管道的使用和文件一致,迎合了“Linux一切且文件的思想”
3.5管道实例
3.5.1测试管道读写
1#include <iostream> 2#include <unistd.h> 3#include <sys/wait.h> 4#include <cstdio> 5#include <cstring> 6 7void ChildWrite(int wfd){ 8 int cnt=0; 9 while(true){ 10 char buf[1024]; 11 snprintf(buf,sizeof(buf),"I am child,pid=%d,%d",getpid(),cnt++); 12 write(wfd,buf,strlen(buf)); 13 sleep(1); 14 } 15} 16void FatherRead(int rfd){ 17 while(true){ 18 char buf[1024]; 19 int n=read(rfd,buf,sizeof(buf)-1); 20 if(n>0){ 21 buf[n]=0; 22 std::cout<<"child say:"<<buf<<std::endl; 23 } 24 } 25} 26int main(){ 27 int fds[2]={0};//fds[0] read ,fds[1] write 28 pipe(fds); 29 int fd=fork(); 30 if(fd==0){ 31 //child 32 //关闭不需要的读写端 33 //f -> r, c -> w 34 close(fds[0]); 35 ChildWrite(fds[1]); 36 close(fds[1]); 37 } 38 //father 39 //关闭不需要的读写端 40 //f -> r, c -> w 41 close(fds[1]); 42 FatherRead(fds[0]); 43 close(fds[0]); 44 waitpid(fd,nullptr,0); 45 return 0; 46}
3.5.2创建进程池处理任务
ProcessPool.hpp
1#ifndef __PROCESS_POOL_HPP__ //防止同一个头文件被重复包含 2#define __PROCESS_POOL_HPP__ 3 4#include <iostream> 5#include <vector> 6#include <cstdlib> 7#include <unistd.h> 8#include <sys/wait.h> 9#include "Task.hpp" 10 11class Channel{ 12public: 13 Channel(int fd,pid_t subid):_fd(fd),_subid(subid) 14 { 15 _name="channel-"+std::to_string(_fd)+"-"+std::to_string(_subid); 16 } 17 void Send(int taskcode){ 18 int n=write(_fd,&taskcode,sizeof(taskcode)); 19 (void)n;//消除编译器警告 20 } 21 void Close(){ 22 close(_fd); 23 } 24 void Wait(){ 25 pid_t rid=waitpid(_subid,nullptr,0); 26 (void)rid; 27 } 28 ~Channel(){} 29 int Fd(){return _fd;} 30 int SubId(){return _subid;} 31 std::string Name(){return _name;} 32private: 33 int _fd; 34 int _subid; 35 std::string _name; 36}; 37 38class ChannelManager{ 39public: 40 ChannelManager():_next(0) 41 {} 42 void Insert(int wfd,pid_t subid){ 43 _channels.emplace_back(wfd,subid); 44 } 45 Channel &Select(){ 46 auto &c=_channels[_next]; 47 _next++; 48 _next%=_channels.size(); 49 return c; 50 } 51 void CloseAll(){ 52 for(auto &channel:_channels){ 53 channel.Close(); 54 } 55 } 56 void TestSlove(){ 57 for(int i=_channels.size()-1;i>=0;i--){ 58 _channels[i].Close(); 59 _channels[i].Wait(); 60 std::cout<<"等待子进程"<<_channels[i].Name()<<std::endl; 61 } 62 } 63 void CloseAndWait(){ 64 for(auto &c:_channels){ 65 c.Close(); 66 c.Wait(); 67 std::cout<<"等待子进程"<<c.Name()<<std::endl; 68 } 69 } 70 void StopChannel(){ 71 for(auto &c:_channels){ 72 c.Close(); 73 std::cout<<"关闭管道"<<c.Name()<<std::endl; 74 } 75 } 76 void WaitSubProcess(){ 77 for(auto &c:_channels){ 78 c.Wait(); 79 std::cout<<"等待子进程"<<c.Name()<<std::endl; 80 } 81 } 82 ~ChannelManager(){} 83private: 84 std::vector<Channel> _channels; 85 int _next; 86}; 87 88int gdefaultnum = 5; 89 90class ProcessPool{ 91public: 92 ProcessPool(int num):_process_num(num) 93 { 94 _tm.Register(Task1); 95 _tm.Register(Task2); 96 _tm.Register(Task3); 97 } 98 void Work(int rfd){ 99 while(true){ 100 int code=0; 101 ssize_t n=read(rfd,&code,sizeof(code)); 102 if(n>0){ 103 if(n!=sizeof(code)){ 104 continue; 105 } 106 std::cout<<"子进程["<<getpid()<<"]收到一个任务码:"<<code<<std::endl; 107 _tm.Excute(code); 108 } 109 else if(n==0){ 110 std::cout<<"子进程退出"<<std::endl; 111 break; 112 } 113 else{ 114 std::cout<<"read error"<<std::endl; 115 break; 116 } 117 } 118 } 119 bool Start(){ 120 for(int i=0;i<_process_num;i++){ 121 //创建管道 122 int pfd[2]={0}; 123 int n=pipe(pfd); 124 125 if(n<0){ 126 std::cout<<"pipe error"<<std::endl; 127 return false; 128 } 129 130 pid_t subid=fork(); 131 if(subid<0){ 132 std::cout<<"fork error"<<std::endl; 133 return false; 134 } 135 else if(subid==0){ 136 //child 137 //关闭不需要的读/写端 138 //child -> read 139 close(pfd[1]); 140 Work(pfd[0]); 141 _cm.CloseAll(); 142 close(pfd[0]); 143 exit(0); 144 } 145 else{ 146 //father 147 //关闭不需要的读/写端 148 //father -> write 149 close(pfd[0]); 150 _cm.Insert(pfd[1],subid); 151 } 152 } 153 return true; 154 } 155 void Run(){ 156 //1.选择一个任务 157 int taskcode=_tm.Code(); 158 //2.选择一个信道[子进程],负载均衡的选择 159 auto &c=_cm.Select(); 160 std::cout<<"选择了一个子进程"<<c.Name()<<std::endl; 161 //3.发送任务 162 c.Send(taskcode); 163 std::cout<<"发送了一个任务码"<<taskcode<<std::endl; 164 } 165 166 void Stop(){ 167 // //关闭管道 168 // _cm.StopChannel(); 169 // //结束子进程 170 // _cm.WaitSubProcess(); 171 172 //_cm.CloseAndWait(); 173 //两个进程合在一起会报错,这是因为创建进程时产生的问题 174 //原因:父进程创建子进程时,子进程会拷贝一份进程描述符表,当父进程的4号描述符指向管道文件的w端, 175 //而3号指向r端,但是父进程是写入,所以3号被关闭,此时子进程1中还正常,只有父进程4号指向管道文件的w端 176 //但子进程2中,父进程3号指向r端,5号指向w端,由于复制了父进程的描述符表所以子进程2的4也指向子进程1的w端, 177 //以致于剩下的子进程都指向之前的子进程w端,导致关闭子进程时,因为有多个w端指向子进程所以无法正常关闭 178 179 //解决方法一:倒着关闭子进程 180 //_cm.TestSlove(); 181 182 //解决方法二:在创建这些子进程的时候就关闭掉它们的复制父进程的w端(Start()中添加) 183 _cm.StopChannel(); 184 185 _cm.WaitSubProcess(); 186 } 187 ~ProcessPool(){} 188private: 189 ChannelManager _cm; 190 int _process_num; 191 TaskManager _tm; 192}; 193 194#endif 195
Task.hpp
1#pragma once 2 3#include <iostream> 4#include <vector> 5#include <cstdlib> 6#include <ctime> 7 8//函数指针 9typedef void (*func_t)(); 10 11void Task1(){ 12 std::cout<<"Task1 is write system log"<<std::endl; 13} 14void Task2(){ 15 std::cout<<"Task2 is upload"<<std::endl; 16} 17void Task3(){ 18 std::cout<<"Task3 is download"<<std::endl; 19} 20 21class TaskManager{ 22public: 23 TaskManager(){ 24 srand(time(nullptr)); 25 } 26 void Register(func_t f){ 27 _tasks.push_back(f); 28 } 29 int Code(){ 30 return rand()%_tasks.size(); 31 } 32 void Excute(int code){ 33 if(code>=0&&code<_tasks.size()){ 34 _tasks[code](); 35 } 36 } 37 ~TaskManager(){} 38private: 39 std::vector<func_t> _tasks; 40};
main.cc
1#include "ProcessPool.hpp" 2 3int main(){ 4 //创建进程池对象 5 ProcessPool pp(gdefaultnum); 6 //启动进程池 7 pp.Start(); 8 9 int cnt=10; 10 while(cnt--){ 11 pp.Run(); 12 sleep(1); 13 } 14 15 //结束任务 16 pp.Stop(); 17 return 0; 18}
Makefile
1process_pool:main.cc 2 g++ -o $@ $^ -std=c++11 3.PHONY:clean 4clean: 5 rm -f process_pool
3.6管道读写规则
●当没有数据可读时
▢O_NONBLOCK disable:read调用阻塞,即进程暂停执行,一直等到有数据来为止
▢O_NONBLOCK enable:read调用返回-1,errno值为EAGAIN
●当管道满的时候
▢O_NONBLOCK disable:write调用阻塞,直到有进程读走数据
▢O_NONBLOCK enable:调用返回-1,errno值为EAGAIN
●若所有管道写端对应的文件描述符被关闭,则read返回0
●若所以有管道读端对应的文件描述符被关闭,则write操作会产生信号SIGPIPE,进而可能导致write进程退出
●当要写入的数据量不大于PIPE_BUF时,Linux将保证写入的原子性(单次write()系统调用写入管道/FIFO的数据,作为一个不可分割的整体进入管道,不会和其它进程的write()数据相互交错)
●当要写入的数据量大于PIPE_BUF时,Linux将保证写入的原子性
3.7管道特性
●只能用于具有共同祖先的进程(具有亲缘关系的进程)之间进行通信。通常,一个管道由一个进程创建,然后该进程调用fork,此后父、子进程之间就可应用该管道
●管道提供流式服务
●一般而言,进程退出,管道释放,所以管道的生命周期随进程
●一般而言,内核会对管道操作进行同步和互斥
●管道是半双工的,数据只能向一个方向流动;需要双方通信时,需要建立起两个管道

3.8验证管道通信的4种情况
●读正常&&写满
●写正常&&读空
●写关闭&&读正常
●读关闭&&写正常
4.命名管道
●管道应用的一个限制就是只能在具有共同祖先(具有亲缘关系)的进程间通信
●若想不在不相关的进程间交换数据,可以使用FIFO文件来做这项工作,被称为命名管道
●命名管道是一种特殊类型的文件
4.1创建一个命名管道
●命名管道可以从命令行上创建,命令行方法是使用下面这个命令
$ mkfifo filename
●命名管道也可以从程序里创建,相关函数:
int mkfifo(const char* fifename,mode_t mode);
●创建命名管道
1int main(int argc, char *argv[]) 2{ 3 mkfifo("p2", 0644); 4 return 0; 5} 6
4.2匿名管道与命名管道的区别
●匿名管道由pipe函数创建并打开
●命名管道由mkfifo函数创建,用open打开
●FIFO(命名管道)与pipe(匿名管道)之间唯一的区别在于它们创建和打开的方式不同,一旦这些工作完成之后,它们具有相同的语义(都是文件上的操作)
4.3命名管道的打开规则
●若当前打开操作是为读而打开FIFO时
▢O_NONBLOCK disable:阻塞直到有相应进程为写而打开该FIFO
▢O_NONBLOCK enable:立即返回成功
●若当前打开操作是为写而打开FIFO时
▢O_NONBLOCK disable:阻塞直到有相应进程为读而打开该FIFO
▢O_NONBLOCK enable:立即返回失败,错误码为ENXIO
实例1:用命名管道实现文件拷贝
读取文件,写入命名管道
1#include <unistd.h> 2#include <stdlib.h> 3#include <stdio.h> 4#include <errno.h> 5#include <string.h> 6 7#define ERR_EXIT(m) \ 8do \ 9{ \ 10 perror(m); \ 11 exit(EXIT_FAILURE); \ 12} while(0) 13 14int main(int argc, char *argv[]) 15{ 16 mkfifo("tp", 0644); 17 int infd; 18 infd = open("abc", O_RDONLY); 19 if (infd == -1) ERR_EXIT("open"); 20 int outfd; 21 outfd = open("tp", O_WRONLY); 22 if (outfd == -1) ERR_EXIT("open"); 23 char buf[1024]; 24 int n; 25 while ((n=read(infd, buf, 1024))>0) 26 { 27 write(outfd, buf, n); 28 } 29 close(infd); 30 close(outfd); 31 return 0; 32} 33
读取管道,写入目标文件
1#include <unistd.h> 2#include <stdlib.h> 3#include <stdio.h> 4#include <errno.h> 5#include <string.h> 6 7#define ERR_EXIT(m) \ 8do \ 9{ \ 10 perror(m); \ 11 exit(EXIT_FAILURE); \ 12} while(0) 13 14int main(int argc, char *argv[]) 15{ 16 int outfd; 17 outfd = open("abc.bak", O_WRONLY | O_CREAT | O_TRUNC, 0644); 18 if (outfd == -1) ERR_EXIT("open"); 19 int infd; 20 infd = open("tp", O_RDONLY); 21 if (outfd == -1) 22 ERR_EXIT("open"); 23 char buf[1024]; 24 int n; 25 while ((n=read(infd, buf, 1024))>0) 26 { 27 write(outfd, buf, n); 28 } 29 close(infd); 30 close(outfd); 31 unlink("tp"); 32 return 0; 33} 34
实例2:用命名管道实现server&client通信
Makefile
1.PHONY:all 2all:server client 3server:server.cc 4 g++ -o $@ $^ 5client:client.cc 6 g++ -o $@ $^ 7 8.PHONY:clean 9clean: 10 rm -f server client
comm.hpp
1#pragma once 2 3#include <iostream> 4#include <cstdio> 5#include <sys/types.h> 6#include <sys/stat.h> 7#include <unistd.h> 8#include <fcntl.h> 9#include <string> 10 11#define PATH "." 12#define FIFONAME "fifo" 13 14#define ERR_EXIT(n) \ 15do{ \ 16 perror(n); \ 17 exit(EXIT_FAILURE); \ 18}while(0) \ 19 20class FileFifo{ 21public: 22 FileFifo(const std::string &path,const std::string &name) 23 :_path(path),_name(name) 24 { 25 _pathname=_path+"/"+_name; 26 umask(0); 27 //创建管道文件 28 int n=mkfifo(_pathname.c_str(),0666); 29 if(n<0){ 30 std::cerr<<"mkfifo error"<<std::endl; 31 ERR_EXIT("mkfifo"); 32 } 33 } 34 ~FileFifo(){ 35 //删除管道文件 36 int n=unlink(_pathname.c_str()); 37 if(n==0){ 38 std::cout<<"unlink success"<<std::endl; 39 } 40 else{ 41 std::cerr<<"remove fifo failed"<<std::endl; 42 ERR_EXIT("unlink"); 43 } 44 } 45private: 46 std::string _path; 47 std::string _name; 48 std::string _pathname; 49}; 50 51class FifoOper{ 52public: 53 FifoOper(const std::string &path,const std::string &name) 54 :_path(path),_name(name),_fd(-1) 55 { 56 _pathname=_path+"/"+_name; 57 } 58 void OpenForRead(){ 59 //打开文件 60 //当write没有执行open时,read会在open内部进行阻塞 61 //直到有人把管道文件打开了,open才会返回 62 _fd=open(_pathname.c_str(),O_RDONLY); 63 if(_fd<0){ 64 std::cerr<<"open mkfifo failed"<<std::endl; 65 ERR_EXIT("open"); 66 } 67 std::cout<<"open fifo success"<<std::endl; 68 } 69 void OpenForWrite(){ 70 //打开文件 71 _fd=open(_pathname.c_str(),O_WRONLY); 72 if(_fd<0){ 73 std::cerr<<"open mkfifo failed"<<std::endl; 74 ERR_EXIT("open"); 75 } 76 std::cout<<"open fifo success"<<std::endl; 77 } 78 void Reader(){ 79 //读取文件内容 80 char buffer[1024]; 81 while(true){ 82 int n=read(_fd,buffer,sizeof(buffer)-1); 83 if(n>0){ 84 buffer[n]=0; 85 std::cout<<"Client say# "<<buffer<<std::endl; 86 } 87 else if(n==0){ 88 std::cout<<"Client quit,me too"<<std::endl; 89 break; 90 } 91 else { 92 std::cout<<"read error"<<std::endl; 93 ERR_EXIT("read"); 94 } 95 } 96 } 97 void Writer(){ 98 //向文件写入内容 99 std::string message; 100 int cnt=1; 101 pid_t id=getpid(); 102 while(true){ 103 std::cout<<"Please say# "; 104 std::getline(std::cin,message); 105 message+=(",message number:"+std::to_string(cnt++)+",["+std::to_string(id)+"]"); 106 write(_fd,message.c_str(),message.size()); 107 } 108 } 109 void Close(){ 110 if(_fd>0) 111 close(_fd); 112 } 113 ~FifoOper(){} 114private: 115 std::string _path; 116 std::string _name; 117 std::string _pathname; 118 int _fd; 119};
server.cc
1#include "comm.hpp" 2 3int main(){ 4 FileFifo fifo(PATH,FIFONAME); 5 6 FifoOper readerfile(PATH,FIFONAME); 7 readerfile.OpenForRead(); 8 readerfile.Reader(); 9 readerfile.Close(); 10 return 0; 11}
client.cc
1#include "comm.hpp" 2 3int main(){ 4 FifoOper writerfile(PATH,FIFONAME); 5 writerfile.OpenForWrite(); 6 writerfile.Writer(); 7 writerfile.Close(); 8 return 0; 9}
结果:

参考文档
- Primers 编程伙伴/C/API 帮助手册/stdio.h
- Primers 编程伙伴/C/API 帮助手册/stdlib.h
- Primers 编程伙伴/C/API 帮助手册/string.h
- Primers 编程伙伴/C/标准库/perror
- Primers 编程伙伴/C/标准库/exit
- Primers 编程伙伴/C/标准库/fgets
- Primers 编程伙伴/C/标准库/strlen
- Primers 编程伙伴/C/标准库/memset
- Primers 编程伙伴/C/标准库/ctime
- Primers 编程伙伴/C/标准库/system
- Primers 编程伙伴/C/标准库/srand
- Primers 编程伙伴/C/标准库/time
- Primers 编程伙伴/C/标准库/rand
- Primers 编程伙伴/C/API 帮助手册/errno.h
- Primers 编程伙伴/C/标准库/remove
《Linux系统——进程间通信之管道》 是转载文章,点击查看原文。
