Windows下进程间共享内存

写个进程间的共享内存的简单示例

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;
}

运行结果

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值