进程间通信(2) 内存映射FileMap
生活随笔
收集整理的這篇文章主要介紹了
进程间通信(2) 内存映射FileMap
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
1.文件映射對象。
- 文件映射對象是內核對象,它從系統的分頁文件中獲得一段內存。
- 所有內核對象都共享同一個名字空間,所以名稱不能重復。
- 其他內核對象還有:事件,信號,互斥對象
2. 創建一個文件映射對象。
- 為文件映射指明一個大小和名稱。
- windows api:CreateFileMapping
3. 對內核對象進行讀寫操作
windows api:MapViewOfFile
4. 示例
FULL_MAP_NAME 用來標記文件映射對象
server
// Prepare a message to be written to the view. PWSTR pszMessage = (PWSTR)MESSAGE;DWORD cbMessage = (wcslen(pszMessage) + 1) * sizeof(*pszMessage);HANDLE hMapFile = NULL;PVOID pView = NULL;// Create the file mapping object. hMapFile = CreateFileMapping(INVALID_HANDLE_VALUE, // Use paging file - shared memory NULL, // Default security attributes PAGE_READWRITE, // Allow read and write access 0, // High-order DWORD of file mapping max size MAP_SIZE, // Low-order DWORD of file mapping max size FULL_MAP_NAME // Name of the file mapping object );if (hMapFile == NULL){wprintf(L"CreateFileMapping failed w/err 0x%08lx\n", GetLastError());goto Cleanup;}wprintf(L"The file mapping (%s) is created\n", FULL_MAP_NAME);// Map a view of the file mapping into the address space of the current // process. pView = MapViewOfFile(hMapFile, // Handle of the map object FILE_MAP_ALL_ACCESS, // Read and write access 0, // High-order DWORD of the file offset VIEW_OFFSET, // Low-order DWORD of the file offset VIEW_SIZE // The number of bytes to map to view );if (pView == NULL){wprintf(L"MapViewOfFile failed w/err 0x%08lx\n", GetLastError());goto Cleanup;}wprintf(L"The file view is mapped\n");// Write the message to the view. memcpy_s(pView, VIEW_SIZE, pszMessage, cbMessage);wprintf(L"This message is written to the view:\n\"%s\"\n",pszMessage);client
HANDLE hMapFile = NULL;PVOID pView = NULL;// Try to open the named file mapping identified by the map name. hMapFile = OpenFileMapping(FILE_MAP_READ, // Read access FALSE, // Do not inherit the name FULL_MAP_NAME // File mapping name );if (hMapFile == NULL){wprintf(L"OpenFileMapping failed w/err 0x%08lx\n", GetLastError());goto Cleanup;}wprintf(L"The file mapping (%s) is opened\n", FULL_MAP_NAME);// Map a view of the file mapping into the address space of the current // process. pView = MapViewOfFile(hMapFile, // Handle of the map object FILE_MAP_READ, // Read access 0, // High-order DWORD of the file offset VIEW_OFFSET, // Low-order DWORD of the file offset VIEW_SIZE // The number of bytes to map to view );if (pView == NULL){wprintf(L"MapViewOfFile failed w/err 0x%08lx\n", GetLastError());goto Cleanup;}wprintf(L"The file view is mapped\n");// Read and display the content in view. wprintf(L"Read from the file mapping:\n\"%s\"\n", (PWSTR)pView);結果:
【引用】
[1]: 代碼地址 https://github.com/thefistlei/os/tree/main/processCommunication/fileMap
總結
以上是生活随笔為你收集整理的进程间通信(2) 内存映射FileMap的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 区块链BaaS云服务(9)索尼 区块链通
- 下一篇: 区块链BaaS云服务(10)用友iuap