[学习记录]C++进程间共享内存

来源:互联网 发布:antpool矿池挖矿软件 编辑:程序博客网 时间:2024/06/05 16:33

一个进程内创建共享内存空间,其余只用绑定这片内存即可实现进程间内存的共享。

即一个进程创建,其余进程打开。


定义句柄

HANDLE hMapFile = NULL;PVOID pView = NULL;

某一进程

创建共享内存空间

// Create the file mapping object.hMapFile = CreateFileMapping(INVALID_HANDLE_VALUE,// Use paging file - shared memoryNULL,// Default security attributesPAGE_READWRITE,// Allow read and write access0,// High-order DWORD of file mapping max sizeMAP_SIZE,// Low-order DWORD of file mapping max sizeFULL_MAP_NAME// Name of the file mapping object);

指定内存的指针

// Map a view of the file mapping into the address space of the current// process.pView = MapViewOfFile(hMapFile,// Handle of the map objectFILE_MAP_ALL_ACCESS,// Read and write access0,// High-order DWORD of the file offsetVIEW_OFFSET,// Low-order DWORD of the file offsetVIEW_SIZE// The number of bytes to map to view);

共享所需数据

memcpy_s(pView, VIEW_SIZE, pszMessage, cbMessage);


其余进程

不用创建,只需打开被共享的那片内存即可

hMapFile = OpenFileMapping(FILE_MAP_READ, // Read accessFALSE, // Do not inherit the nameFULL_MAP_NAME // File mapping name);


指定内存的指针

// Map a view of the file mapping into the address space of the current// process.pView = MapViewOfFile(hMapFile,// Handle of the map objectFILE_MAP_ALL_ACCESS,// Read and write access0,// High-order DWORD of the file offsetVIEW_OFFSET,// Low-order DWORD of the file offsetVIEW_SIZE// The number of bytes to map to view);

共享所需数据

memcpy_s(pView, VIEW_SIZE, pszMessage, cbMessage);



共享内存的保护则后续再议~~~~~

0 0