转载请注明来源:https://www.cnblogs.com/hookjc/

C++使用共享内存实现进程间通信
文件映射是一种实现进程间单向或双向通信的机制。它允许两个或多个本地进程间相互通信。为了共享文件或内存,所有的进程必须使用相同的文件映射的名字或是句柄。
为了实现共享文件,第一个进程先调用CreateFile方法。接下来调用CreateFileMapping方法来创建一个文件映射对象。并为文件映射指明一个句柄和名称。由于事件,信号,互斥对象和文件映射等这些内核对象都共享同一个名字空间,所以如果这个名字和其他一个对象的名称重名的话那么将创建失败。
为了实现共享内存,进程应首先调用CreateFileMapping函数然后在hFile参数中传入INVALID_HANDLE_VALUE宏来替代句柄。相应的文件映射对象会从系统的分页文件中获得一段内存。如果hFile参数的值是INVALID_HANDLE_VALUE,那么你在调用CreateFileMapping时必须给共享内存指定一个大小值。
使用共享内存或文件的进程必须使用MapViewOfFile函数或MapViewOfFileEx函数来创建一个文件视图。
下面我们创建一个名称为"Local\SampleMap"的文件映射对象,并将一个字符串写入到文件映射中。
我们将创建两个程序,一个是服务程序,一个是客户程序。服务程序负责创建文件映射。
服务程序命名为CppFileMappingServer,它的执行过程是
1.创建一个特定大小的文件映射对象,名称为“Local\SampleMap”
2.将这个对象的文件视图映射到进程的地址空间,然后向视图中写入字符串。

接下来执行客户程序CppFileMappingClient,它首先打开这个名称为“Local\SampleMap”的文件映射对象。然后把相同的文件映射视图映射到自己的地址空间中。然后从视图中读取服务进程所写入的数据。

Server完整源码:

  1. #pragma region Includes
  2. #include <stdio.h>
  3. #include <windows.h>
  4. #pragma endregion
  5. #define MAP_PREFIX          L"Local\\"
  6. #define MAP_NAME            L"SampleMap"
  7. #define FULL_MAP_NAME       MAP_PREFIX MAP_NAME
  8. // Max size of the file mapping object.
  9. #define MAP_SIZE            65536
  10. // File offset where the view is to begin.
  11. #define VIEW_OFFSET         0
  12. // The number of bytes of a file mapping to map to the view. All bytes of the
  13. // view must be within the maximum size of the file mapping object (MAP_SIZE).
  14. // If VIEW_SIZE is 0, the mapping extends from the offset (VIEW_OFFSET) to
  15. // the end of the file mapping.
  16. #define VIEW_SIZE           1024
  17. // Unicode string message to be written to the mapped view. Its size in byte
  18. // must be less than the view size (VIEW_SIZE).
  19. #define MESSAGE             L"Message from the first process."
  20. int wmain(int argc, wchar_t* argv[])
  21. {
  22. HANDLE hMapFile = NULL;
  23. PVOID pView = NULL;
  24. // Create the file mapping object.
  25. hMapFile = CreateFileMapping(
  26. INVALID_HANDLE_VALUE,   // Use paging file - shared memory
  27. NULL,                   // Default security attributes
  28. PAGE_READWRITE,         // Allow read and write access
  29. 0,                      // High-order DWORD of file mapping max size
  30. MAP_SIZE,               // Low-order DWORD of file mapping max size
  31. FULL_MAP_NAME           // Name of the file mapping object
  32. );
  33. if (hMapFile == NULL)
  34. {
  35. wprintf(L"CreateFileMapping failed w/err 0x%08lx\n", GetLastError());
  36. goto Cleanup;
  37. }
  38. wprintf(L"The file mapping (%s) is created\n", FULL_MAP_NAME);
  39. // Map a view of the file mapping into the address space of the current
  40. // process.
  41. pView = MapViewOfFile(
  42. hMapFile,               // Handle of the map object
  43. FILE_MAP_ALL_ACCESS,    // Read and write access
  44. 0,                      // High-order DWORD of the file offset
  45. VIEW_OFFSET,            // Low-order DWORD of the file offset
  46. VIEW_SIZE               // The number of bytes to map to view
  47. );
  48. if (pView == NULL)
  49. {
  50. wprintf(L"MapViewOfFile failed w/err 0x%08lx\n", GetLastError());
  51. goto Cleanup;
  52. }
  53. wprintf(L"The file view is mapped\n");
  54. // Prepare a message to be written to the view.
  55. PWSTR pszMessage = MESSAGE;
  56. DWORD cbMessage = (wcslen(pszMessage) + 1) * sizeof(*pszMessage);
  57. // Write the message to the view.
  58. memcpy_s(pView, VIEW_SIZE, pszMessage, cbMessage);
  59. wprintf(L"This message is written to the view:\n\"%s\"\n",
  60. pszMessage);
  61. // Wait to clean up resources and stop the process.
  62. wprintf(L"Press ENTER to clean up resources and quit");
  63. getchar();
  64. Cleanup:
  65. if (hMapFile)
  66. {
  67. if (pView)
  68. {
  69. // Unmap the file view.
  70. UnmapViewOfFile(pView);
  71. pView = NULL;
  72. }
  73. // Close the file mapping object.
  74. CloseHandle(hMapFile);
  75. hMapFile = NULL;
  76. }
  77. return 0;
  78. }

Client完整源码

  1. #pragma region Includes
  2. #include <stdio.h>
  3. #include <windows.h>
  4. #pragma endregion
  5. #define MAP_PREFIX          L"Local\\"
  6. #define MAP_NAME            L"SampleMap"
  7. #define FULL_MAP_NAME       MAP_PREFIX MAP_NAME
  8. // File offset where the view is to begin.
  9. #define VIEW_OFFSET         0
  10. // The number of bytes of a file mapping to map to the view. All bytes of the
  11. // view must be within the maximum size of the file mapping object. If
  12. // VIEW_SIZE is 0, the mapping extends from the offset (VIEW_OFFSET) to the
  13. // end of the file mapping.
  14. #define VIEW_SIZE           1024
  15. int wmain(int argc, wchar_t* argv[])
  16. {
  17. HANDLE hMapFile = NULL;
  18. PVOID pView = NULL;
  19. // Try to open the named file mapping identified by the map name.
  20. hMapFile = OpenFileMapping(
  21. FILE_MAP_READ,          // Read access
  22. FALSE,                  // Do not inherit the name
  23. FULL_MAP_NAME           // File mapping name
  24. );
  25. if (hMapFile == NULL)
  26. {
  27. wprintf(L"OpenFileMapping failed w/err 0x%08lx\n", GetLastError());
  28. goto Cleanup;
  29. }
  30. wprintf(L"The file mapping (%s) is opened\n", FULL_MAP_NAME);
  31. // Map a view of the file mapping into the address space of the current
  32. // process.
  33. pView = MapViewOfFile(
  34. hMapFile,               // Handle of the map object
  35. FILE_MAP_READ,          // Read access
  36. 0,                      // High-order DWORD of the file offset
  37. VIEW_OFFSET,            // Low-order DWORD of the file offset
  38. VIEW_SIZE               // The number of bytes to map to view
  39. );
  40. if (pView == NULL)
  41. {
  42. wprintf(L"MapViewOfFile failed w/err 0x%08lx\n", GetLastError());
  43. goto Cleanup;
  44. }
  45. wprintf(L"The file view is mapped\n");
  46. // Read and display the content in view.
  47. wprintf(L"Read from the file mapping:\n\"%s\"\n", (PWSTR)pView);
  48. // Wait to clean up resources and stop the process.
  49. wprintf(L"Press ENTER to clean up resources and quit");
  50. getchar();
  51. Cleanup:
  52. if (hMapFile)
  53. {
  54. if (pView)
  55. {
  56. // Unmap the file view.
  57. UnmapViewOfFile(pView);
  58. pView = NULL;
  59. }
  60. // Close the file mapping object.
  61. CloseHandle(hMapFile);
  62. hMapFile = NULL;
  63. }
  64. return 0;
  65. }

运行效果:

Server


Client

来源:python脚本自动迁移

Window 共享内存的更多相关文章

  1. [转]WINDOW进程间数据通讯以及共享内存

    1.引言 在Windows程序中,各个进程之间常常需要交换数据,进行数据通讯.WIN32 API提供了许多函数使我们能够方便高效地进行进程间的通讯,通过这些函数我们可以控制不同进程间的数据交换,就如同 ...

  2. Fresco内存机制(Ashmem匿名共享内存)

    Fresco的内存机制 Fresco是Facebook出品的高性能图片加载库,采用了Ashmem匿名共享内存机制, 来解决图片加载中的OOM问题.这里不对Fresco做深入分析,只关注Fresco在A ...

  3. C扩展 从共享内存shm到memcache外部内存

    引言 - ipc - shm 共享内存 本文会通过案例了解ipc 的共享内存机制使用, 后面会讲解C 如何使用外部内存服务memcached. 好先开始了解 linux 共享内存机制. 推荐先参看下面 ...

  4. Codesys 使用共享内存 打通通讯

    Codesys V3.5 平台   提供了库SysShm,其中包含了共享内存操作的接口函数: SysSharedMemoryClose; SysSharedMemoryCreate; SysShare ...

  5. Linux 共享内存详解一

    共享内存段被多个进程附加的时候,如果不是所有进程都已经调用shmdt,那么删除该共享内存段时,会出现一个临时的不完整的共享内存段(key值是0),无法彻底删除.只有当所有进程都调用shmdt,这个临时 ...

  6. PHP进程通信基础——信号量+共享内存通信

    PHP进程通信基础--信号量+共享内存通信 由于进程之间谁先执行并不确定,这取决于内核的进程调度算法,其中比较复杂.由此有可能多进程在相同的时间内同时访问共享内存,从而造成不可预料的错误.信号量这个名 ...

  7. C++ 共享内存 函数封装

    #pragma once #include <string> #include <wtypes.h> #include <map> using namespace ...

  8. Linux学习笔记(14)-进程通信|共享内存

    在Linux中,共享内存是允许两个不相关的进程访问同一个逻辑内存的进程间通信方法,是在两个正在运行的进程之间共享和传递数据的一种非常有效的方式. 不同进程之间共享的内存通常安排为同一段物理内存.进程可 ...

  9. linux 共享内存 shmat,shmget,shmdt,shmctl

    shmget int shmget(key_t key, size_t size, int flag);//开辟一段共享内存 key_t key :标识符的规则() size_t size :共享内存 ...

随机推荐

  1. BL8810最新版规格书|BL8810方案|USB 2.0读卡器控制器

    在数码产品越来越普及的今天,利用单反.手机.平板等产品随手拍下相片.储存一些非常重要的数据等已经成为很多人必做的事情,而除使用数据线进行数据导入导出的操作外,利用读卡器也是一个必然的选择,就以本人自己 ...

  2. 云南农业职业技术学院 / 互联网技术学院官网 HTML5+CSS3

    HTML学完后写了,有小组成员参与开发,我只写了主页,那就只贴主页的代码出来了. 作为初学者,代码写得不太好,写博客纯属记录!有问题望指导! 码云开源仓库地址:https://gitee.com/yn ...

  3. .NetCore下构建自己的文件服务管理(UosoOSS)

    Web开发系统文件默认存储在wwwroot目录下面,现在越来越多的系统服务化了,UI也更加多元化,当然文件可以用第三方的文件服务,但是这里准备文件分离出来构建自己的文件服务配合数据库表来实现(Uoso ...

  4. 接口调试没有登录态?用whistle帮你解决

    页面的域名是 a.com,接口的域名为 b.com,这是跨域的因此不会将 cookie 带过去的,也就没有登录态. 解决方法:利用 whistle 的 composer 功能. whistle git ...

  5. CentOS 7安装Etherpad(在线协作编辑)

    Etherpad 是一个线上共制平台,是基于网络的实时合作文档编辑器,三.四个人可以坐在自己电脑前,同时对一份文档修改,也同时能看到其他人的修改. CentOS 7 安装 Etherpad 1.先安装 ...

  6. 微信小程序css继承

    在微信小程序里写的全局样式,pages里的组件是可以继承的,但是components里只能继承font和color属性.

  7. javascript中new url()属性,轻松解析url地址

    1.首先写一个假的地址(q=URLUtils.searchParams&topic=api)相当于当前的window.location.href const urlParams = new U ...

  8. 关于CKCsec安全研究院

    关于CKCsec安全研究院 CKCsec安全研究院所有文档开源于语雀,会源源不断更新. 部分内容 微信公众号 知识星球 使用需知 由于传播.利用此文所提供的信息而造成的任何直接或者间接的后果及损失,均 ...

  9. 【原创】阿里三面:搞透Kafka的存储架构,看这篇就够了

    阅读本文大约需要30分钟.这篇文章干货很多,希望你可以耐心读完. 你好, 我是华仔,在这个 1024 程序员特殊的节日里,又和大家见面了. 从这篇文章开始,我将对 Kafka 专项知识进行深度剖析, ...

  10. 开源数据可视化BI工具SuperSet(安装)

    本次安装教程共分两大步骤,因为Superset 基于python3编写的web应用(flask) 所以要求python3环境,故首先要将linux系统自带的环境进行升级,已经是python3的可跳过- ...