注意

使用system创建的共享内存,使用普通用户读取,创建时要设置权限 。

1
2
permissions ps;
ps.set_unrestricted(); // 0666

使用shared_memory_object创建的共享内存不会随着对象的释放而删除。

使用windows_shared_memory创建的共享内存会随着对象的释放而删除,并且跨用户读取时,共享对象名前面需要加上"Global\\"表名是全局共享内存。

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68

#include <boost/interprocess/shared_memory_object.hpp>
#include <boost/interprocess/mapped_region.hpp>
#include <boost/interprocess/windows_shared_memory.hpp>

#define USE_WIN_SHARE_MEMORY 0

// 创建
bool ShareMemory::CreateShare(const std::string& key, const std::string& value)
{
using namespace boost::interprocess;
try
{
#if USE_WIN_SHARE_MEMORY
permissions ps;
ps.set_unrestricted(); // 0666
m_impl->wsm = std::make_shared<windows_shared_memory>(boost::interprocess::open_or_create, key.c_str(), read_write, value.length() + 1, ps);
boost::interprocess::mapped_region region(*m_impl->wsm, read_write);
std::memset(region.get_address(), 0, region.get_size());
std::memcpy(region.get_address(), value.c_str(), value.length());
#else
permissions ps;
ps.set_unrestricted(); // 0666
shared_memory_object smo(boost::interprocess::open_or_create, key.c_str(), read_write, ps);
smo.truncate(value.length() + 1);
boost::interprocess::mapped_region region(smo, read_write);
std::memset(region.get_address(), 0, region.get_size());
std::memcpy(region.get_address(), value.c_str(), value.length());

#endif
return true;
}
catch (std::exception& e)
{
LOG_ERROR("open or create share memory error %s! %s, %s", e.what(), key.c_str(), value.c_str());
return false;
}
return false;
}
// 读取
bool ShareMemory::ReadShare(const std::string& key, std::string& value)
{
using namespace boost::interprocess;
try
{
#if USE_WIN_SHARE_MEMORY
m_impl->wsm = std::make_shared<windows_shared_memory>(open_only, key.c_str(), read_only);
mapped_region region(*m_impl->wsm, read_only);
char* port = static_cast<char*>(region.get_address());
value = port;
return true;
#else
boost::interprocess::shared_memory_object shm(boost::interprocess::open_only, key.c_str(), boost::interprocess::read_only);
boost::interprocess::mapped_region region(shm, boost::interprocess::read_only);
char* port = static_cast<char*>(region.get_address());
value = port;

#endif
return true;
}
catch (std::exception& e)
{
LOG_ERROR("read share memory error %s! %s, %s", e.what(), key.c_str(), value.c_str());
return false;
}
return false;
}