c++ 共享内存demo
时间: 2024-06-22 19:00:47
浏览: 5
在C++中,共享内存是一种进程间通信(IPC)的技术,可以让多个进程直接访问同一块内存[区域](https://geek.csdn.net/educolumn/372157e1bc734b976821bd070a509a57?spm=1055.2569.3001.10083),而无需经过文件、网络或[消息](https://geek.csdn.net/educolumn/20acd77092e0c464c067a69674f1ed19?spm=1055.2569.3001.10083)队列等中间环节。以下是一个简单的C++共享内存的demo示例,使用`boost::interprocess`库:
```cpp
#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/[map](https://geek.csdn.net/educolumn/489f40071d2cdbfb1748ab6a5a24440e?spm=1055.2569.3001.10083)ped_region.hpp>
#include <cstdlib>
#include <c[string](https://geek.csdn.net/edu/8802d631b97a4a6af1f4d0bbf8527465?dp_token=eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpZCI6NDQ0MDg2MiwiZXhwIjoxNzA3MzcxOTM4LCJpYXQiOjE3MDY3NjcxMzgsInVzZXJuYW1lIjoid2VpeGluXzY4NjQ1NjQ1In0.RrTYEnMNYPC7AQdoij4SBb0kKEgHoyvF-bZOG2eGQvc&spm=1055.2569.3001.10083)>
// 创建共享内存
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::[run](https://geek.csdn.net/educolumn/15da07d43c7a20f5ec210826be35c36c?spm=1055.2569.3001.10083)time_error("Could not create shared memory");
shm.tru
```