windows下实现共享内存
进程A写入共享内存:
#include <stdio.h>
#include <windows.h>int main() {// 创建或打开共享内存对象HANDLE hMapFile = CreateFileMapping(INVALID_HANDLE_VALUE,NULL,PAGE_READWRITE,0,4096, // 内存大小,这里为4KBTEXT("SharedMemory")); // 共享内存名称,进程B也需要使用相同的名称来打开共享内存if (hMapFile == NULL) {printf("Could not create file mapping object (%d).\n", GetLastError());return 1;}// 将共享内存映射到当前进程的地址空间LPVOID pBuf = MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, 4096);if (pBuf == NULL) {printf("Could not map view of file (%d).\n", GetLastError());CloseHandle(hMapFile);return 1;}// 写入数据到共享内存strcpy((char *)pBuf, "Hello from Process A");printf("Data written to shared memory: %s\n", (char *)pBuf);// 保持进程运行,以便观察效果while (1) {Sleep(1000);}// 清理资源UnmapViewOfFile(pBuf);CloseHandle(hMapFile);return 0;
}
进程B读取共享内存:
#include <stdio.h>
#include <windows.h>int main() {// 打开共享内存对象HANDLE hMapFile = OpenFileMapping(FILE_MAP_READ,FALSE,TEXT("SharedMemory")); // 使用与进程A相同的共享内存名称if (hMapFile == NULL) {printf("Could not open file mapping object (%d).\n", GetLastError());return 1;}// 将共享内存映射到当前进程的地址空间LPVOID pBuf = MapViewOfFile(hMapFile, FILE_MAP_READ, 0, 0, 4096);if (pBuf == NULL) {printf("Could not map view of file (%d).\n", GetLastError());CloseHandle(hMapFile);return 1;}// 从共享内存读取数据printf("Data read from shared memory: %s\n", (char *)pBuf);// 清理资源UnmapViewOfFile(pBuf);CloseHandle(hMapFile);return 0;
}