• Linux——进程间通信(管道及共享内存)


    目录

    0. 前言

    1. 进程通信的目的

    2. 进程通信发展及分类

    3. 进程通信匿名管道

    3.1 什么是管道?

    3.2 匿名管道系统调用

    3.3 fork后子进程继承(基于内存级)

    3.4 站在文件描述符角度-深度理解管道

    3.5 站在内核角度-管道本质

    3.6 父子进程单向通信示例代码

    3.7 管道读写规则

    3.8 总结管道特点,理解|管道

    3.9 派发任务—单机版负载均衡

    4. 进程通信命名管道

    4.1 命名管道

    4.2 命名管道系统调用

    4.3 命名管道与匿名管道及读写规则

    4.4 示例用命名管道实现server&client通信

    5. system V共享内存

    5.1 共享内存示意图

    5.2 共享内存数据结构

    5.3 共享内存系统调用

    1. 共享内存的创建及key_t:

    2. 共享内存关联进程:

    3. 解除关联该进程的共享内存:

    4. 删除共享内存:

    5.4  命名管道访问控制共享内存

    5.5 共享内存总结

    6. system V消息队列 — 选学

    7. system V信号量 — 选学


    0. 前言

    进程具有独立性:

            进程想要通信,难度其实是比较大的

    进程通信的本质:

            先让不同进程看到同一份资源(内存空间)

            所以进程看到同一块“内存”,不能隶属于任何一个进程,更应该强调共享

    为什么要进行进程通信?

            交互数据,控制,通知等的目标

    进程间通信的必要性?

            单进程无法使用并发能力,更加无法实现多进程协同

            进程间通信是一种手段,目的是为了实现多进程协同

    1. 进程通信的目的

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

    2. 进程通信发展及分类

    主流通信标准:

    • 管道
    • System V进程间通信(接口复杂,不能很好整合文件场景,侧重于本地通信)
    • POSIX进程间通信(多线程,将网络通信纳入,即能本地通信,又能网络编程通信,写出代码具有高扩展高可用性)

    进程间通信分类:

    管道:匿名管道pipe,命名管道

    System V IPC: System V 消息队列,System V 共享内存,System V 信号量

    POSIX IPC: 消息队列,共享内存,信号量,互斥量,条件变量,读写锁

    3. 进程通信匿名管道

    3.1 什么是管道?

    管道是Unix中最古老的进程间通信的形式。

    我们把从一个进程连接到另一个进程的一个数据流称为一个“管道”

    管道都是单向传输内容的,传输的都是“资源”(计算机通信领域设计的一种单项通信方式)

    因为进程具有独立性,因此管道不能是进程给你的,一定是操作系统提供的,可以使用某种方式使用管道进行通信

    3.2 匿名管道系统调用

    #include

    功能:创建一无名管道

    原型 int pipe(int fd[2]);

    参数 fd:文件描述符数组,其中fd[0]表示读端, fd[1]表示写端

    返回值:成功返回0,失败返回-1错误代码 and errno is set appropriately.

    3.3 fork后子进程继承(基于内存级)

    fork之后,子进程会继承父进程的PCB(环境变量,命令行参数,task_struct)、地址空间、页表,并且会继承文件描述符表(stdin、stdout、stderr及其他父进程打开文件,此时,父子进程操作同一个文件),并不会新创建拷贝一个同名文件!

    此时父子进程就看到同一份文件资源,这份资源就叫做管道,而如果文件存在磁盘上,每次读写都需要刷新到磁盘,且管道文件只是负责进程间通信,并不负责保存数据,因此在内存上创建管道文件能大幅度提高通信效率,操作系统便提供系统调用pipe创建内存级的匿名管道,匿名管道文件生命周期一般都是随父子进程的生命周期!

    3.4 站在文件描述符角度-深度理解管道

    1. 父进程创建管道

    2. 父进程fork创建子进程

    3. 父进程关闭fd[0],子进程关闭fd[1]

    3.5 站在内核角度-管道本质

    看待管道,就如同看待文件一样!管道的使用和文件一致,迎合了“Linux一切皆文件思想”。

    父子进程task_struct -> files_struct* files -> struct file* fd_array[] -> 找到对应文件描述符对应的file结构体 -> 内部含有f_inode、读写操作方法函数指针数组f_op -> 进行读写操作  

    3.6 父子进程单向通信示例代码

    1. #include <iostream>
    2. #include <assert.h>
    3. #include <string>
    4. #include <cstdio>
    5. #include <cstring>
    6. #include <unistd.h>
    7. #include <sys/types.h>
    8. #include <sys/wait.h>
    9. using namespace std;
    10. int main()
    11. {
    12. // 1. 创建管道
    13. // int pipe(int pipefd[2]) 输出型参数,期望调用,得到被打开文件fd
    14. // 创建成功返回0, 失败返回-1
    15. int pipefd[2] = {0}; // pipefd[0] 读端 pipefd[1] 写端
    16. int n = pipe(pipefd);
    17. assert(n != -1);
    18. (void)n; // 避免release版本下报警问题,debug assert not use
    19. #ifdef DEBUG
    20. cout << "pipefd[0]:" << pipefd[0] << endl; // 3
    21. cout << "pipefd[1]:" << pipefd[1] << endl; // 4
    22. #endif
    23. // 2. 创建子进程
    24. pid_t id = fork();
    25. assert(id != -1);
    26. if (id == 0)
    27. {
    28. // 3. 构建单向通信的信道,子进程读取
    29. // 3.1 关闭子进程不需要的fd
    30. close(pipefd[1]);
    31. char buffer[1024 * 8];
    32. int count = 0;
    33. while (true)
    34. {
    35. // 3.2 故意sleep,写的快,读慢,具有访问控制
    36. //sleep(20);
    37. //写入一方,fd没有关闭,如果有数据,就读,没有就等
    38. //写入一方,fd关闭,读取的一方,read返回0,表示读到了文件结尾!
    39. ssize_t s = read(pipefd[0], buffer, sizeof(buffer) - 1);
    40. if (s > 0)
    41. {
    42. buffer[s] = '\0';
    43. cout << "child get a message[" << getpid() << "] frome Father# " << buffer << endl;
    44. }else if(s == 0){
    45. cout << "write quit(father), me quit!" << endl;
    46. break;
    47. }
    48. }
    49. // close(pipefd[0]);
    50. exit(0);
    51. }
    52. // 3. 构建单向通信的信道,父进程写入
    53. // 3.1 关闭子进程不需要的fd
    54. close(pipefd[0]);
    55. string message = "我是父进程,我在给你发消息";
    56. int count = 0;
    57. char send_buffer[1024];
    58. while (true)
    59. {
    60. // 3.2 构建一个变化的字符串
    61. snprintf(send_buffer, sizeof(send_buffer), "%s[%d] : %d",
    62. message.c_str(), getpid(), count);
    63. // 3.3 发送(写入)
    64. ssize_t s = write(pipefd[1], send_buffer, strlen(send_buffer));
    65. count++;
    66. assert(s != -1);
    67. sleep(1);
    68. //cout << count << endl;
    69. if(count == 10){
    70. break;
    71. }
    72. }
    73. close(pipefd[1]);
    74. pid_t ret = waitpid(id, nullptr, 0);
    75. assert(ret != -1);
    76. (void)ret;
    77. //close(pipefd[1]);
    78. return 0;
    79. }

    3.7 管道读写规则

    a. 写快,读慢,写满就不能再写了,等待读取后才可以写

    b. 写慢,读快,管道没有数据的时候,读必须等待

    c. 写关,读0,表示读到文件结尾

    d. 读关,写继续写,OS终止写进程

    当没有数据可读时

    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将保证写入的原子性。

    当要写入的数据量大于PIPE_BUF时,linux将不再保证写入的原子性。

    3.8 总结管道特点,理解|管道

    1. 管道是用来进行具有血缘关系的进程,进行进程间通信(常用于父子进程)

    只能用于具有共同祖先的进程(具有亲缘关系的进程)之间进行通信;通常,一个管道由一个进程创建,然后该进程调用fork,此后父、子进程之间就可应用该管道。

    2. 管道具有能通过让进程协同,提供访问控制

    管道是一个文件 - 读取时需要等待管道文件被写入  -  具有访问控制

    显示器也是一个文件,父子进程同时往显示器写入的时候,有没有说一个会等另一个的情况呢?  -  缺乏访问控制

    3. 管道提供的时面向流式的通信服务 —— 面向字节流 —— 定制协议

    4. 一般而言,内核会对管道操作进行同步与互斥

    6. 管道是基于文件的,文件的生命周期一般是随进程的,因此管道的生命周期一般也随进程的!

    7. 管道是单向通信的,就是半双工通信(要么收,要么发)的一种特殊情况,数据只能向一个方向流动;需要双方通信时,需要建立起两个管道

    3.9 派发任务—单机版负载均衡

    由父进程创建多个子进程,对每个进程创建管道,每个子进程等待父进程写入,派发任务,执行对应的任务,而父进程写入不同的管道(文件描述符),调用的便是不同的进程,写入的内容便是派发的具体任务!

    task.hpp

    1. #pragma once
    2. #include<iostream>
    3. #include<unistd.h>
    4. #include<string>
    5. #include<functional>
    6. #include<vector>
    7. #include<map>
    8. //typedef std::function<void()> func;
    9. using func = std::function<void()>;
    10. std::vector<func> callBacks;
    11. std::map<int, std::string> desc;
    12. void readMySQL(){
    13. std::cout << "new process[ " << getpid() << " ]执行访问数据库的任务\n" << std::endl;
    14. }
    15. void execuleURL(){
    16. std::cout << "new process[ " << getpid() << " ]执行url解析\n" << std::endl;
    17. }
    18. void cal(){
    19. std::cout << "new process[ " << getpid() << " ]执行加密任务\n" << std::endl;
    20. }
    21. void save(){
    22. std::cout << "new process[ " << getpid() << " ]执行数据持久化任务\n" << std::endl;
    23. }
    24. void load(){
    25. desc.insert({callBacks.size(), "readMySQL"});
    26. callBacks.push_back(readMySQL);
    27. desc.insert({callBacks.size(), "execuleURL"});
    28. callBacks.push_back(execuleURL);
    29. desc.insert({callBacks.size(), "cal"});
    30. callBacks.push_back(cal);
    31. desc.insert({callBacks.size(), "save"});
    32. callBacks.push_back(save);
    33. }
    34. void showHandler(){
    35. for(const auto& iter : desc){
    36. std::cout << iter.first << "\t" << iter.second << std::endl;
    37. }
    38. }
    39. int handlerSize(){
    40. return callBacks.size();
    41. }

    proPool.cc

    1. #include<iostream>
    2. #include<vector>
    3. #include<unistd.h>
    4. #include<sys/types.h>
    5. #include<sys/wait.h>
    6. #include<cassert>
    7. #include"task.hpp"
    8. using namespace std;
    9. #define PROCESS_NUM 5
    10. int waitCommand(int waitFd, bool& quit)
    11. {
    12. uint32_t command = 0;
    13. ssize_t s = read(waitFd, &command, sizeof(command));
    14. //assert(s == sizeof(uint32_t));
    15. if(s == 0){
    16. quit = true;
    17. return -1;
    18. }
    19. return command;
    20. }
    21. void sendAndWakeUp(pid_t who, int fd, uint32_t command)
    22. {
    23. write(fd, &command, sizeof(command));
    24. cout << "main call process : " << who << " execute : \"" << desc[command] << "\" through : " << fd << endl;
    25. }
    26. int main(){
    27. load();
    28. // pid : pipefd 键值对
    29. vector<pair<pid_t,int>> slots;
    30. for(int i = 0; i < 5; ++i){
    31. int pipefd[2] = {0};
    32. int pp = pipe(pipefd);
    33. assert(pp != -1);
    34. (void)pp;
    35. int id = fork();
    36. assert(id != -1);
    37. (void)id;
    38. if(id == 0){
    39. close(pipefd[1]);
    40. while(true){
    41. bool quit = false;
    42. int command = waitCommand(pipefd[0], quit);
    43. if(quit){
    44. break;
    45. }
    46. if (command >= 0 && command < handlerSize())
    47. {
    48. callBacks[command]();
    49. }
    50. else
    51. {
    52. cout << "非法command : " << command << endl;
    53. }
    54. }
    55. exit(0);
    56. }
    57. close(pipefd[0]);
    58. slots.push_back({id, pipefd[1]});
    59. }
    60. srand((unsigned int)time(nullptr) ^ getpid() ^ 233323123123L); // 让数据源更加随机
    61. while(true){
    62. int choice = rand() % slots.size();
    63. int command = rand() % handlerSize();
    64. sendAndWakeUp(slots[choice].first, slots[choice].second, command);
    65. sleep(1);
    66. }
    67. // while (true)
    68. // {
    69. // int select;
    70. // int command;
    71. // sleep(1);
    72. // cout << "###############################################" << endl;
    73. // cout << "# 1. show functions 2. send commend " << endl;
    74. // cout << "###############################################" << endl;
    75. // cout << "Please Select> ";
    76. // cin >> select;
    77. // if (select == 1)
    78. // {
    79. // showHandler();
    80. // }
    81. // else if (select == 2)
    82. // {
    83. // cout << "Enter Your Command>";
    84. // cin >> command;
    85. // // 选择进程
    86. // int choice = rand() % slots.size();
    87. // // 布置任务
    88. // sendAndWakeUp(slots[choice].first, slots[choice].second, command);
    89. // }
    90. // else
    91. // {
    92. // break;
    93. // }
    94. // }
    95. for(const auto &iter : slots){
    96. close(iter.second);
    97. }
    98. for(const auto &slot : slots){
    99. pid_t s = waitpid(slot.first, nullptr, 0);
    100. assert(s != -1);
    101. }
    102. return 0;
    103. }

    4. 进程通信命名管道

    4.1 命名管道

    • 管道应用的一个限制就是只能在具有共同祖先(具有亲缘关系)的进程间通信。
    • 如果我们想在不相关的进程之间交换数据,可以使用FIFO文件来做这项工作,它经常被称为命名管道。
    • 命名管道是一种特殊类型的文件,可以被打开,但是不会将内存数据刷新到磁盘

    4.2 命名管道系统调用

    $命名管道可以从命令行上创建,命令行方法是使用下面这个命令:

            $ mkfifo filename

    $命名管道也可以从程序里创建,相关函数有:

            int mkfifo(const char *filename,mode_t mode);

    头文件:

             #include
             #include

    返回值:

            On success mkfifo() returns 0.  In the case of an error, -1 is returned (in which case, errno is set appropriately).

    当要写入的数据量不大于PIPE_BUF时,linux将保证写入的原子性。4096

    当要写入的数据量大于PIPE_BUF时,linux将不再保证写入的原子性。

    创建命名管道:

    1. #include
    2. #include
    3. #include
    4. int main(int argc, char *argv[])
    5. {
    6. mkfifo("p2", 0644);
    7. return 0;
    8. }

    4.3 命名管道与匿名管道及读写规则

    • 匿名管道由pipe函数创建并打开。
    • 命名管道由mkfifo函数创建,打开用open
    • FIFO(命名管道)与pipe(匿名管道)之间唯一的区别在它们创建与打开的方式不同,一但这些工作完成之后,它们具有相同的语义。

    如果当前打开操作是为读而打开FIFO时

    O_NONBLOCK disable:阻塞直到有相应进程为写而打开该FIFO

    O_NONBLOCK enable:立刻返回成功

    如果当前打开操作是为写而打开FIFO时

    O_NONBLOCK disable:阻塞直到有相应进程为读而打开该FIFO

    O_NONBLOCK enable:立刻返回失败,错误码为ENXIO

    4.4 示例用命名管道实现server&client通信

    log.hpp _ 输出日志信息

    1. #ifndef _LOG_H_
    2. #define _LOG_H_
    3. #include <iostream>
    4. #include <ctime>
    5. #include <string>
    6. #define Error 0
    7. #define Warning 1
    8. #define Notice 2
    9. #define Debug 3
    10. const std::string msg[] = {
    11. "Error",
    12. "Warning",
    13. "Notice",
    14. "Debug"
    15. };
    16. std::ostream &Log(const std::string message, int level)
    17. {
    18. std::cout << " | " << (unsigned)time(nullptr) << " | " << msg[level] << " | " << message;
    19. return std::cout;
    20. }
    21. #endif

    comm.h _ 头文件

    1. #ifndef _COMM_H_
    2. #define _COMM_H_
    3. #include
    4. #include
    5. #include
    6. #include
    7. #include
    8. #include
    9. #include
    10. #include
    11. #include
    12. #include "log.hpp"
    13. using namespace std;
    14. #define MODE 0666
    15. #define BUFSZ 128
    16. string ipcPath = "./fifo.ipc";
    17. #endif
    18. #include
    19. #include
    20. #include
    21. #include
    22. #include

    server.cxx

    1. #include "comm.hpp"
    2. #include <sys/wait.h>
    3. static void getMessage(int fd)
    4. {
    5. // 3.编写正常通信代码
    6. char buffer[BUFSZ] = {0};
    7. while (true)
    8. {
    9. memset(buffer, '\0', sizeof(buffer));
    10. ssize_t s = read(fd, buffer, sizeof(buffer) - 1);
    11. if (s > 0)
    12. {
    13. buffer[s] = '\0';
    14. cout << "[" << getpid() << "] "
    15. << "server from client say :" << buffer << endl;
    16. }
    17. else if (s == 0)
    18. {
    19. // end of file
    20. cout << "[" << getpid() << "] "
    21. << "read end of file, client quit, server quit too!" << endl;
    22. break;
    23. }
    24. else
    25. {
    26. perror("read");
    27. exit(3);
    28. }
    29. }
    30. }
    31. int main()
    32. {
    33. // 1.创建管道文件
    34. if (mkfifo(ipcPath.c_str(), MODE) == -1)
    35. {
    36. perror("mkfifo");
    37. exit(1);
    38. }
    39. Log("创建管道文件成功", Debug) << " |step 1" << endl;
    40. // 2.正常文件操作
    41. int fd = open(ipcPath.c_str(), O_RDONLY);
    42. if (fd == -1)
    43. {
    44. perror("open");
    45. exit(2);
    46. }
    47. Log("打开管道文件成功", Debug) << " |step 2" << endl;
    48. int nums = 3;
    49. for (int i = 0; i < nums; ++i)
    50. {
    51. pid_t id = fork();
    52. if (id == 0)
    53. {
    54. getMessage(fd);
    55. exit(4);
    56. }
    57. }
    58. for (int i = 0; i < nums; ++i)
    59. {
    60. waitpid(-1, nullptr, 0);
    61. }
    62. // 3.编写正常通信代码
    63. // getMessage(fd);
    64. // 4.关闭文件
    65. close(fd);
    66. Log("关闭管道文件成功", Debug) << " |step 3" << endl;
    67. // 5.通信完毕,删除管道文件
    68. unlink(ipcPath.c_str());
    69. Log("删除管道文件成功", Debug) << " |step 4" << endl;
    70. return 0;
    71. }

    client.cxx

    1. #include"comm.hpp"
    2. int main(){
    3. //1.打开管道文件
    4. int fd = open(ipcPath.c_str(), O_WRONLY);
    5. if(fd == -1){
    6. perror("open");
    7. exit(1);
    8. }
    9. //2.编写正常通信代码
    10. string buffer;
    11. while(true){
    12. cout << "Please Enter Message Line (Enter Exit):> ";
    13. getline(cin, buffer);
    14. ssize_t s = write(fd, buffer.c_str(), buffer.size());
    15. if(s == -1){
    16. perror("write");
    17. exit(2);
    18. }else if(s == 0){
    19. cout << "Exit client !" << endl;
    20. break;
    21. }
    22. }
    23. //3.关闭管道文件
    24. close(fd);
    25. return 0;
    26. }

    5. system V共享内存

    共享内存区是最快的IPC形式。一旦这样的内存映射到共享它的进程的地址空间,这些进程间数据传递不再涉及到内核,换句话说是进程不再通过执行进入内核的系统调用来传递彼此的数据

    system V IPC资源,生命周期随内核(手动删除 #ipcrm -m shmid,代码删除)

    5.1 共享内存示意图

    共享内存不属于任何一个进程,属于操作系统

    堆栈之间共享区域:属于操作系统,还是属于用户呢? —— 属于用户,用户空间 (32位下,进程地址空间0-3G属于用户,1G属于内核),用户空间意味着,拿到后不用使用系统调用,可以直接使用!

    获取到共享内存后,双方进程如果要通信,直接进行内存级的读和写即可

    5.2 共享内存数据结构

    共享内存由操作系统维护,因此需要有对应的数据结构维护

    1. struct shmid_ds {
    2. struct ipc_perm shm_perm; /* operation perms */
    3. int shm_segsz; /* size of segment (bytes) */
    4. __kernel_time_t shm_atime; /* last attach time */
    5. __kernel_time_t shm_dtime; /* last detach time */
    6. __kernel_time_t shm_ctime; /* last change time */
    7. __kernel_ipc_pid_t shm_cpid; /* pid of creator */
    8. __kernel_ipc_pid_t shm_lpid; /* pid of last operator */
    9. unsigned short shm_nattch; /* no. of current attaches */
    10. unsigned short shm_unused; /* compatibility */
    11. void *shm_unused2; /* ditto - used by DIPC */
    12. void *shm_unused3; /* unused */
    13. };

    共享内存 = 共享内存块 + 对应的共享内存的内核数据结构

    5.3 共享内存系统调用

    1. 共享内存的创建及key_t:

    shmget函数:

    1. 功能:用来创建共享内存
    2. 原型
    3. int shmget(key_t key, size_t size, int shmflg);
    4. 参数
    5. key:这个共享内存段名字
    6. size:共享内存大小
    7. shmflg:IPC_CREAT and IPC_EXCL 两个选项
    8. 返回值:成功返回一个非负整数,即该共享内存段的标识码;失败返回-1

    shmget参数中shmflg选项含义:

    • 单独使用IPC_CREAT:如果创建共享内存时,若底层已经存在,获取之,并且返回,如果不存在,创建之,并返回
    • 单独适应IPC_EXCL:没有意义
    • 共同使用:如果底层不存在,创建并返回,如果存在,出错返回,因此,返回的一定是一个新的shm!

    ftok函数:只有创建的时候用key,大部分情况用户访问共享内存,都用的shmid

    1. NAME
    2. ftok - convert a pathname and a project identifier to a System V IPC
    3. key
    4. SYNOPSIS
    5. #include <sys/types.h>
    6. #include <sys/ipc.h>
    7. key_t ftok(const char *pathname, int proj_id);
    8. RETURN VALUE
    9. On success, the generated key_t value is returned. On failure -1 is
    10. returned, with errno indicating the error as for the stat(2) system
    11. call.

    2. 共享内存关联进程:

    shmat函数:

    1. 功能:将共享内存段连接到进程地址空间
    2. 原型
    3. void *shmat(int shmid, const void *shmaddr, int shmflg);
    4. 参数
    5. shmid: 共享内存标识
    6. shmaddr:指定连接的地址
    7. shmflg:它的两个可能取值是SHM_RND和SHM_RDONLY
    8. 返回值:成功返回一个指针,指向共享内存第一个节;失败返回-1

    说明:

    shmaddr为NULL,核心自动选择一个地址

    shmaddr不为NULL,且shmflg无SHM_RND标记,则以shmaddr为连接地址。

    shmaddr不为NULL,且shmflg设置了SHM_RND标记,则连接的地址会自动向下调整为SHMLBA的整数倍。

    公式:shmaddr - (shmaddr % SHMLBA) shmflg=SHM_RDONLY,表示连接操作用来只读共享内存

    3. 解除关联该进程的共享内存:

    shmdt函数:

    1. 功能:将共享内存段与当前进程脱离
    2. 原型
    3. int shmdt(const void *shmaddr);
    4. 参数
    5. shmaddr: 由shmat所返回的指针
    6. 返回值:成功返回0;失败返回-1
    7. 注意:将共享内存段与当前进程脱离不等于删除共享内存段

    4. 删除共享内存:

    shmctl函数:

    1. 功能:用于控制共享内存
    2. 原型
    3. int shmctl(int shmid, int cmd, struct shmid_ds *buf);
    4. 参数
    5. shmid:由shmget返回的共享内存标识码
    6. cmd:将要采取的动作(有三个可取值)
    7. buf:指向一个保存着共享内存的模式状态和访问权限的数据结构
    8. 返回值:成功返回0;失败返回-1

    sgmctl函数中cmd选项:

    1. IPC_STAT Copy information from the kernel data structure associated
    2. with shmid into the shmid_ds structure pointed to by buf.
    3. The caller must have read permission on the shared memory
    4. segment.
    5. IPC_SET Write the values of some members of the shmid_ds structure
    6. pointed to by buf to the kernel data structure associated
    7. with this shared memory segment, updating also its
    8. shm_ctime member. The following fields can be changed:
    9. shm_perm.uid, shm_perm.gid, and (the least significant 9
    10. bits of) shm_perm.mode. The effective UID of the calling
    11. process must match the owner (shm_perm.uid) or creator
    12. (shm_perm.cuid) of the shared memory segment, or the call
    13. er must be privileged.
    14. IPC_RMID Mark the segment to be destroyed. The segment will only
    15. actually be destroyed after the last process detaches it
    16. (i.e., when the shm_nattch member of the associated struc‐
    17. ture shmid_ds is zero). The caller must be the owner or
    18. creator, or be privileged. If a segment has been marked
    19. for destruction, then the (nonstandard) SHM_DEST flag of
    20. the shm_perm.mode field in the associated data structure
    21. retrieved by IPC_STAT will be set.
    22. The caller must ensure that a segment is eventually
    23. destroyed; otherwise its pages that were faulted in will
    24. remain in memory or swap.

    5.4  命名管道访问控制共享内存

    log.hpp

    1. #ifndef _LOG_H_
    2. #define _LOG_H_
    3. #include <iostream>
    4. #include <ctime>
    5. #include <string>
    6. #define Error 0
    7. #define Warning 1
    8. #define Notice 2
    9. #define Debug 3
    10. const std::string msg[] = {
    11. "Error",
    12. "Warning",
    13. "Notice",
    14. "Debug"
    15. };
    16. std::ostream &Log(const std::string message, int level)
    17. {
    18. std::cout << " | " << (unsigned)time(nullptr) << " | " << msg[level] << " | " << message;
    19. return std::cout;
    20. }
    21. #endif

    comm.hpp

    1. #pragma once
    2. #include<iostream>
    3. #include<string>
    4. #include<cstdlib>
    5. #include<cstring>
    6. #include<unistd.h>
    7. #include<sys/stat.h>
    8. #include<sys/types.h>
    9. #include<sys/ipc.h>
    10. #include<sys/shm.h>
    11. #include<fcntl.h>
    12. #include<cassert>
    13. #include"log.hpp"
    14. #define PATH_NAME "/home/customer"
    15. #define PROJ_ID 0x66
    16. //共享内存的大小,最好是页(PAGE4096)的整数倍
    17. #define SHM_SIZE 4096
    18. #define FIFO_NAME "./fifo"
    19. class Init{
    20. public:
    21. Init(){
    22. umask(0);
    23. int n = mkfifo(FIFO_NAME, 0666);
    24. assert(n != -1);
    25. (void)n;
    26. Log("create fifo success", Notice) << std::endl;
    27. }
    28. ~Init(){
    29. unlink(FIFO_NAME);
    30. Log("remove fifo success", Notice) << std::endl;
    31. }
    32. };
    33. #define READ O_RDONLY
    34. #define WRITE O_WRONLY
    35. int openFIFO(std::string pathName, int flags){
    36. int fd = open(pathName.c_str(), flags);
    37. assert(fd != -1);
    38. Log("open fifo sucess", Notice) << std::endl;
    39. return fd;
    40. }
    41. void Wait(int fd){
    42. Log("等待中...", Notice) << std::endl;
    43. uint32_t temp = 0;
    44. ssize_t s = read(fd, &temp, sizeof(uint32_t));
    45. assert(s == sizeof(uint32_t));
    46. (void)s;
    47. }
    48. void Signal(int fd){
    49. Log("唤醒中...", Notice) << std::endl;
    50. uint32_t temp = 1;
    51. ssize_t s = write(fd, &temp, sizeof(uint32_t));
    52. assert(s == sizeof(uint32_t));
    53. (void)s;
    54. }
    55. void closeFIFO(int fd){
    56. Log("close fifo success", Notice) << std::endl;
    57. close(fd);
    58. }

    shmServer.cc

    1. #include"comm.hpp"
    2. Init init;
    3. int main(){
    4. Log("Server process pid is ", Debug) << getpid() << std::endl;
    5. //1.创建公共的key
    6. key_t k = ftok(PATH_NAME, PROJ_ID);
    7. if(k == -1){
    8. perror("ftok");
    9. exit(1);
    10. }
    11. Log("create key done! ", Debug);
    12. printf(" server key : 0x%x\n", k);
    13. //2.创建共享内存 -- 建议创建一个全新的共享内存 -- because this process is 通信的发起者
    14. // IPC_CREAT 没有,建之,返回,有,返回
    15. // IPC_EXCL 存在,报错,单独使用,无意义
    16. // IPC_CREAT | IPC_EXCL 没有,建之,并返回,有,报错 ———— 一定是创建一个新的shm
    17. int shmid = shmget(k, SHM_SIZE, IPC_CREAT | IPC_EXCL | 0666);
    18. // 共享内存创建不删除,第二次以同样key值创建共享内存,便会报错
    19. if(shmid == -1){
    20. perror("shmget");
    21. exit(2);
    22. }
    23. Log("create shm done! ", Debug) << " server shmget() shmid : " << shmid << std::endl;
    24. //sleep(10);
    25. //3.将创建的shared memory,挂接到该进程的地址空间处
    26. char* shmaddr = (char*)shmat(shmid, nullptr, 0);
    27. if(shmaddr == (void*)-1){
    28. perror("shmat");
    29. exit(3);
    30. }
    31. Log("attach shm done! ", Debug) << " server shmat() shmid : " << shmid << std::endl;
    32. //【通信逻辑区
    33. //char buffer[SHM_SIZE];
    34. int fd = openFIFO(FIFO_NAME, READ);
    35. for(;;){
    36. Wait(fd);
    37. printf("%s\n", shmaddr);
    38. if(strcmp(shmaddr, "quit") == 0){
    39. break;
    40. }
    41. //sleep(1);
    42. }
    43. //通信逻辑区】
    44. //sleep(10);
    45. //4.将指定的shared memory,从自己的地址空间处去挂接
    46. int detach = shmdt(shmaddr);
    47. if(detach == -1){
    48. perror("shmdt");
    49. exit(4);
    50. }
    51. Log("detach shm done! ", Debug) << " server shmdt() shmid : " << shmid << std::endl;
    52. //5.删除共享内存,IPC_RMID即便是由进程和当下的shm挂接,依旧删除共享内存
    53. int rmshmid = shmctl(shmid, IPC_RMID, nullptr);
    54. if(rmshmid == -1){
    55. perror("shmctl");
    56. exit(6);
    57. }
    58. Log("delete shm done! ", Debug) << " server shmctl() shmid : " << shmid << std::endl;
    59. closeFIFO(fd);
    60. return 0;
    61. }

    shmClient.cc

    1. #include "comm.hpp"
    2. int main()
    3. {
    4. Log("Client process pid is ", Debug) << getpid() << std::endl;
    5. // 1.创建公共的key
    6. key_t k = ftok(PATH_NAME, PROJ_ID);
    7. Log("create key done! ", Debug);
    8. printf(" server key : 0x%x\n", k);
    9. if (k == -1)
    10. {
    11. perror("ftok");
    12. exit(1);
    13. }
    14. // 2.获取共享内存的id
    15. int shmid = shmget(k, SHM_SIZE, 0);
    16. if (shmid == -1)
    17. {
    18. perror("shmget");
    19. exit(2);
    20. }
    21. Log("create shm done! ", Debug) << " server shmget() shmid : " << shmid << std::endl;
    22. //sleep(10);
    23. // 3.挂接
    24. char *shmaddr = (char *)shmat(shmid, nullptr, 0);
    25. if (shmaddr == (void *)-1)
    26. {
    27. perror("shmat");
    28. exit(3);
    29. }
    30. Log("attach shm done! ", Debug) << " server shmat() shmid : " << shmid << std::endl;
    31. // 【通信逻辑区
    32. int fd = openFIFO(FIFO_NAME, WRITE);
    33. while ((true))
    34. {
    35. size_t i = 0;
    36. shmaddr[i] = std::cin.get();
    37. while(shmaddr[i] != '\n'){
    38. shmaddr[++i] = std::cin.get();
    39. }
    40. shmaddr[i] = 0;
    41. // std::cin >> shmaddr;
    42. Signal(fd);
    43. if(strcmp(shmaddr, "quit") == 0){
    44. break;
    45. }
    46. }
    47. // char a = 'a';
    48. // for (; a <= 'z'; a++)
    49. // {
    50. // shmaddr[a - 'a'] = a;
    51. // shmaddr[a - 'a' + 1] = '\0';
    52. // sleep(1);
    53. // // snprintf(shmaddr, SHM_SIZE - 1,
    54. // // "hello serve,我是 Client 进程,我的pid:%d,inc:%c\n", getpid(), a);
    55. // // sleep(5);
    56. // }
    57. // strcpy(shmaddr, "quit");
    58. // 通信逻辑区】
    59. //sleep(20);
    60. // 4.去挂接
    61. int detach = shmdt(shmaddr);
    62. if (detach == -1)
    63. {
    64. perror("shmdt");
    65. exit(4);
    66. }
    67. Log("detach shm done! ", Debug) << " server shmdt() shmid : " << shmid << std::endl;
    68. closeFIFO(fd);
    69. return 0;
    70. }

    5.5 共享内存总结

    结论1:只要是通信双方使用shm,一方直接向共享内存中写入数据,另一方,就可以立马看到对方写入的数据!

    共享内存是所有进程间通信IPC,速度最快的!原因 : 不需要过多的拷贝(不需要陷入内核,不需要将数据给操作系统)!!!

    结论2:共享内存缺乏访问控制!会带来并发问题!

    注意:共享内存没有进行同步与互斥!

    6. system V消息队列 — 选学

    • 消息队列提供了一个从一个进程向另外一个进程发送一块数据的方法
    • 每个数据块都被认为是有一个类型,接收者进程接收的数据块可以有不同的类型值
    • 特性方面: IPC资源必须删除,否则不会自动清除,除非重启,所以system V IPC资源的生命周期随内核

    7. system V信号量 — 选学

    信号量主要用于同步和互斥的,下面先来看看什么是同步和互斥。

    进程互斥:

    • 由于各进程要求共享资源,而且有些资源需要互斥使用,因此各进程间竞争使用这些资源,进程的这种关系为进程的互斥
    • 系统中某些资源一次只允许一个进程使用,称这样的资源为临界资源或互斥资源。
    • 在进程中涉及到互斥资源的程序段叫临界区
    • 特性方面: IPC资源必须删除,否则不会自动清除,除非重启,所以system V IPC资源的生命周期随内核

  • 相关阅读:
    工作失误合集,这个月的工资被扣没咯!
    备战秋招--spring篇
    一套完整的养老院人员定位解决方案包含哪些内容?
    yolov8-OBB检测角度问题
    “大数据分析师”来了,提高职业含金量,欢迎来领
    相约黄浦江畔,汇聚AI与边缘计算的力量
    九、MFC控件(一)
    python技术面试题合集(二)
    A * 算法(机器人路径避障规划)
    大白话讲解TCP三次握手与四次挥手
  • 原文地址:https://blog.csdn.net/IfYouHave/article/details/132746971