【原创】boost共享内存,进程间通信实例

一、发送端创建共享区域,并写入内容:

//1 先删除之前创建的
shared_memory_object::remove("MySharedMemory_Name");

//2 创建共享内存段
shared_memory_object shm(create_only, "MySharedMemory_Name", read_write);

//3 设置共享内存大小
shm.truncate(100);

//4 映射共享内存片段
mapped_region region(shm, read_write);

//5 初始化为0
std::memset(region.get_address(), 0, region.get_size());

//6 往内存里写入数据
string *strTest = static_cast(region.get_address());
*strTest = "hello world";

 

 

二、另一个进程读取内存

//1 读取共享内存
shared_memory_object shm(open_only, "MySharedMemory_Name", read_only);

//2 映射共享内存
mapped_region region(shm, read_only);

//3 检查共享内存是否被初始化为1
string* strRead = static_cast(region.get_address());

 

你可能感兴趣的:(C++,Boost,经验分享)