Window 共享内存

转载请注明来源: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.   
  9. // Max size of the file mapping object.  
  10. #define MAP_SIZE            65536  
  11.   
  12. // File offset where the view is to begin.  
  13. #define VIEW_OFFSET         0  
  14.   
  15. // The number of bytes of a file mapping to map to the view. All bytes of the   
  16. // view must be within the maximum size of the file mapping object (MAP_SIZE).   
  17. // If VIEW_SIZE is 0, the mapping extends from the offset (VIEW_OFFSET) to    
  18. // the end of the file mapping.  
  19. #define VIEW_SIZE           1024  
  20.   
  21. // Unicode string message to be written to the mapped view. Its size in byte   
  22. // must be less than the view size (VIEW_SIZE).  
  23. #define MESSAGE             L"Message from the first process."  
  24.   
  25.   
  26. int wmain(int argc, wchar_t* argv[])  
  27. {  
  28.     HANDLE hMapFile = NULL;  
  29.     PVOID pView = NULL;  
  30.   
  31.     // Create the file mapping object.  
  32.     hMapFile = CreateFileMapping(  
  33.         INVALID_HANDLE_VALUE,   // Use paging file - shared memory  
  34.         NULL,                   // Default security attributes  
  35.         PAGE_READWRITE,         // Allow read and write access  
  36.         0,                      // High-order DWORD of file mapping max size  
  37.         MAP_SIZE,               // Low-order DWORD of file mapping max size  
  38.         FULL_MAP_NAME           // Name of the file mapping object  
  39.         );  
  40.     if (hMapFile == NULL)   
  41.     {  
  42.         wprintf(L"CreateFileMapping failed w/err 0x%08lx\n", GetLastError());  
  43.         goto Cleanup;  
  44.     }  
  45.     wprintf(L"The file mapping (%s) is created\n", FULL_MAP_NAME);  
  46.   
  47.     // Map a view of the file mapping into the address space of the current   
  48.     // process.  
  49.     pView = MapViewOfFile(  
  50.         hMapFile,               // Handle of the map object  
  51.         FILE_MAP_ALL_ACCESS,    // Read and write access  
  52.         0,                      // High-order DWORD of the file offset   
  53.         VIEW_OFFSET,            // Low-order DWORD of the file offset   
  54.         VIEW_SIZE               // The number of bytes to map to view  
  55.         );  
  56.     if (pView == NULL)  
  57.     {   
  58.         wprintf(L"MapViewOfFile failed w/err 0x%08lx\n", GetLastError());   
  59.         goto Cleanup;  
  60.     }  
  61.     wprintf(L"The file view is mapped\n");  
  62.   
  63.     // Prepare a message to be written to the view.  
  64.     PWSTR pszMessage = MESSAGE;  
  65.     DWORD cbMessage = (wcslen(pszMessage) + 1) * sizeof(*pszMessage);  
  66.   
  67.     // Write the message to the view.  
  68.     memcpy_s(pView, VIEW_SIZE, pszMessage, cbMessage);  
  69.   
  70.     wprintf(L"This message is written to the view:\n\"%s\"\n",  
  71.         pszMessage);  
  72.   
  73.     // Wait to clean up resources and stop the process.  
  74.     wprintf(L"Press ENTER to clean up resources and quit");  
  75.     getchar();  
  76.   
  77. Cleanup:  
  78.   
  79.     if (hMapFile)  
  80.     {  
  81.         if (pView)  
  82.         {  
  83.             // Unmap the file view.  
  84.             UnmapViewOfFile(pView);  
  85.             pView = NULL;  
  86.         }  
  87.         // Close the file mapping object.  
  88.         CloseHandle(hMapFile);  
  89.         hMapFile = NULL;  
  90.     }  
  91.   
  92.     return 0;  
  93. }  
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.   
  9. // File offset where the view is to begin.  
  10. #define VIEW_OFFSET         0  
  11.   
  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. If   
  14. // VIEW_SIZE is 0, the mapping extends from the offset (VIEW_OFFSET) to the   
  15. // end of the file mapping.  
  16. #define VIEW_SIZE           1024  
  17.   
  18.   
  19. int wmain(int argc, wchar_t* argv[])  
  20. {  
  21.     HANDLE hMapFile = NULL;  
  22.     PVOID pView = NULL;  
  23.   
  24.     // Try to open the named file mapping identified by the map name.  
  25.     hMapFile = OpenFileMapping(  
  26.         FILE_MAP_READ,          // Read access  
  27.         FALSE,                  // Do not inherit the name  
  28.         FULL_MAP_NAME           // File mapping name   
  29.         );  
  30.     if (hMapFile == NULL)   
  31.     {  
  32.         wprintf(L"OpenFileMapping failed w/err 0x%08lx\n", GetLastError());  
  33.         goto Cleanup;  
  34.     }  
  35.     wprintf(L"The file mapping (%s) is opened\n", FULL_MAP_NAME);  
  36.   
  37.     // Map a view of the file mapping into the address space of the current   
  38.     // process.  
  39.     pView = MapViewOfFile(  
  40.         hMapFile,               // Handle of the map object  
  41.         FILE_MAP_READ,          // Read access  
  42.         0,                      // High-order DWORD of the file offset   
  43.         VIEW_OFFSET,            // Low-order DWORD of the file offset  
  44.         VIEW_SIZE               // The number of bytes to map to view  
  45.         );  
  46.     if (pView == NULL)  
  47.     {  
  48.         wprintf(L"MapViewOfFile failed w/err 0x%08lx\n", GetLastError());   
  49.         goto Cleanup;  
  50.     }  
  51.     wprintf(L"The file view is mapped\n");  
  52.   
  53.     // Read and display the content in view.  
  54.     wprintf(L"Read from the file mapping:\n\"%s\"\n", (PWSTR)pView);  
  55.   
  56.     // Wait to clean up resources and stop the process.  
  57.     wprintf(L"Press ENTER to clean up resources and quit");  
  58.     getchar();  
  59.   
  60. Cleanup:  
  61.   
  62.     if (hMapFile)  
  63.     {  
  64.         if (pView)  
  65.         {  
  66.             // Unmap the file view.  
  67.             UnmapViewOfFile(pView);  
  68.             pView = NULL;  
  69.         }  
  70.         // Close the file mapping object.  
  71.         CloseHandle(hMapFile);  
  72.         hMapFile = NULL;  
  73.     }  
  74.   
  75.     return 0;  
  76. }  
运行效果:

Server


Client

来源:python脚本自动迁移

posted @ 2020-06-23 19:47  jiangcheng_15  阅读(354)  评论(0编辑  收藏  举报