c++ 共享内存demo
时间: 2024-06-22 11:00:47 浏览: 119
C++共享内存示例
4星 · 用户满意度95%
在C++中,共享内存是一种进程间通信(IPC)的技术,可以让多个进程直接访问同一块内存区域,而无需经过文件、网络或消息队列等中间环节。以下是一个简单的C++共享内存的demo示例,使用`boost::interprocess`库:
```cpp
#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <cstdlib>
#include <cstring>
// 创建共享内存
int main() {
// 锁定一个名字为"mySharedMemory",大小为1MB的共享内存
const char* sharedMemName = "mySharedMemory";
const size_t memSize = 1024 * 1024; // 1MB
std::error_code ec;
boost::interprocess::shared_memory_object shm(boost::interprocess::open_or_create, sharedMemName, boost::interprocess::read_write);
if (!shm.IsValid()) {
throw std::runtime_error("Could not create shared memory");
}
shm.truncate(memSize); // 设置共享内存的大小
// 创建映射区域,将共享内存映射到当前进程的地址空间
boost::interprocess::mapped_region region(shm, boost::interprocess::read_write);
void* ptr = region.get_address(); // 获取映射到的内存地址
// 在映射区域写入数据
std::memset(ptr, 'A', memSize);
std::cout << "Wrote to shared memory.\n";
// 在另一个进程中读取数据
std::unique_ptr<boost::interprocess::shared_memory_object> shm2(
new boost::interprocess::shared_memory_object(boost::interprocess::open_only, sharedMemName, boost::interprocess::read_only));
boost::interprocess::mapped_region region2(shm2.get(), boost::interprocess::read_only);
char* ptr2 = static_cast<char*>(region2.get_address());
for (size_t i = 0; i < memSize; ++i) {
if (ptr2[i] == 'A') {
std::cout << "Read value at position " << i << ": A\n";
} else {
std::cout << "Read value at position " << i << ": Not A\n";
}
}
// 关闭映射区域和共享内存
region.close();
shm.close();
return 0;
}
```
阅读全文