写个进程间的共享内存的简单示例
SharedMemoryA通过控制台输入更新共享内存的内容,SharedMemoryB显示。
进程SharedMemoryA代码如下:
#include <iostream>
#include <cstring>
#include <Windows.h>
int main()
{
const char* shared_memory_name = "MySharedMemory";//作为共享内存的唯一标识
const int shared_memory_size = 1024;
// 创建共享内存对象
HANDLE hMapFile = CreateFileMappingA(INVALID_HANDLE_VALUE, NULL, PAGE_READWRITE, 0, shared_memory_size, shared_memory_name);
if (hMapFile == NULL) {
std::cout << "Failed to create shared memory object" << std::endl;
return 1;
}
// 将共享内存映射到当前进程的地址空间
LPVOID lpMapAddress = MapViewOfFile(hMapFile, FILE_MAP_WRITE, 0, 0, shared_memory_size);
if (lpMapAddress == NULL) {
std::cerr << "Failed to map shared memory to address space" << std::endl;
CloseHandle(hMapFile);
return 1;
}
//循环手动更新共享内存的内容
while (true)
{
std::cout << "Please input message:";
char str[shared_memory_size] = { 0 };
std::cin.get(str, shared_memory_size);//键盘获取输入信息
std::cout << "Your input:" << str << std::endl;
// 写入控制台键入的数据到共享内存
std::memcpy(lpMapAddress, str, shared_memory_size);
getchar();
}
// 解除共享内存映射
if (!UnmapViewOfFile(lpMapAddress)) {
std::cerr << "Failed to unmap shared memory from address space" << std::endl;
}
// 关闭共享内存对象的文件句柄(系统将自动释放相关资源)
if (!CloseHandle(hMapFile)) {
std::cerr << "Failed to close shared memory object handle" << std::endl;
}
return 0;
}
SharedMemoryB
#include <iostream>
#include <string>
#include <Windows.h>
int main()
{
// 打开已存在的共享内存对象
HANDLE hMapFile = OpenFileMappingA(FILE_MAP_ALL_ACCESS, FALSE, "MySharedMemory");
if (hMapFile == NULL) {
std::cerr << "Failed to open file mapping object" << std::endl;
return 1;
}
// 将共享内存映射到当前进程的地址空间
LPVOID pBuf = MapViewOfFile(hMapFile, FILE_MAP_ALL_ACCESS, 0, 0, 0);
if (pBuf == NULL) {
std::cerr << "Failed to map view of file" << std::endl;
CloseHandle(hMapFile);
return 1;
}
std::string lastMessage;
while (true)
{
// 访问共享内存中的数据
char* pData = static_cast<char*>(pBuf);
std::string message = pData;
if (lastMessage != message) {
std::cout << "------------------------------- Data in shared memory -----------------------------" << std::endl;
std::cout << "size:" << message.size() << std::endl << "message:" << message << std::endl;
std::cout << "-----------------------------------------------------------------------------------" << std::endl;
lastMessage = message;
}
Sleep(1000);
}
// 解除共享内存映射
if (!UnmapViewOfFile(pBuf)) {
std::cerr << "Failed to unmap shared memory from address space" << std::endl;
}
// 关闭共享内存对象的文件句柄(系统将自动释放相关资源)
if (!CloseHandle(hMapFile)) {
std::cerr << "Failed to close shared memory object handle" << std::endl;
}
return 0;
}
运行结果