SHM
Shared-memorybasedHandy-communicationManager
shared_memory.cpp
1 #include <shm_base.hpp>
2 
3 namespace irlab
4 {
5 
6 namespace shm
7 {
8 
20 int
21 disconnectMemory(std::string name)
22 {
23  if (name[0] == '/')
24  {
25  name = name.erase(0, 1);
26  }
27  std::string str_buf = "/shm_" + regex_replace(name, std::regex("/"), "_");
28  return shm_unlink(str_buf.c_str());
29 }
30 
31 
32 SharedMemory::SharedMemory(int oflag, PERM perm)
33 : shm_fd(-1)
34 , shm_oflag(oflag)
35 , shm_perm(perm)
36 , shm_size(0)
37 , shm_ptr(nullptr)
38 {
39 }
40 
41 
42 SharedMemory::~SharedMemory()
43 {
44  if (shm_fd >= 0)
45  {
46  close(shm_fd);
47  }
48 }
49 
50 
51 size_t
52 SharedMemory::getSize() const
53 {
54  return shm_size;
55 }
56 
57 
58 unsigned char*
59 SharedMemory::getPtr()
60 {
61  return shm_ptr;
62 }
63 
64 SharedMemoryPosix::SharedMemoryPosix(std::string name, int oflag, PERM perm)
65 : SharedMemory(oflag, perm)
66 , shm_name(name)
67 {
68  if (shm_name[0] == '/')
69  {
70  shm_name = shm_name.erase(0, 1);
71  }
72 }
73 
74 
75 SharedMemoryPosix::~SharedMemoryPosix()
76 {
77 }
78 
79 
80 bool
81 SharedMemoryPosix::connect(size_t size)
82 {
83  std::string str_buf = "/shm_" + regex_replace(shm_name, std::regex("/"), "_");
84 
85  shm_fd = shm_open(str_buf.c_str(), shm_oflag, static_cast<mode_t>(shm_perm));
86  if (shm_fd < 0)
87  {
88  return false;
89  }
90  struct stat stat;
91  fstat(shm_fd, &stat);
92  if (size == 0)
93  {
94  shm_size = stat.st_size;
95  } else {
96  shm_size = size;
97  if (stat.st_size < shm_size)
98  {
99  if (ftruncate(shm_fd, shm_size) < 0)
100  {
101  throw std::runtime_error("shm::getMemory(): Could not change shared memory size!");
102  }
103  // To Update stat.st_size
104  fstat(shm_fd, &stat);
105  }
106  }
107  shm_ptr = reinterpret_cast<unsigned char *>(mmap(NULL,
108  stat.st_size,
109  PROT_READ|PROT_WRITE,
110  MAP_SHARED,
111  shm_fd,
112  0));
113 
114  return true;
115 }
116 
117 
118 int
119 SharedMemoryPosix::disconnect()
120 {
121  return disconnectMemory(shm_name);
122 }
123 
124 
125 bool
126 SharedMemoryPosix::isDisconnected() const
127 {
128  struct stat stat;
129  if (shm_fd < 0)
130  {
131  return true;
132  }
133 
134  fstat(shm_fd, &stat);
135  if (stat.st_nlink <= 0)
136  {
137  return true;
138  }
139  return false;
140 }
141 
142 
143 }
144 
145 }
146 
shm_base.hpp
Basic class definitions for accessing shared memory, ring buffers, etc. The notation is complianted R...
irlab::shm::disconnectMemory
int disconnectMemory(std::string name)
共有メモリを破棄する(POSIX版)
Definition: shared_memory.cpp:21