[C++] – A plain simple sample to write to and read from shared memory
If you have two programs ( or two threads ) running on the same computer, you might need a mechanism to share information amongst both programs or transfer values from one program to the other.
One of the possible solutions is “shared memory”. Most of us know shared memory only from server crashes and the like.
Here is a simple sample written in C to show, how you can use a shared memory object. The sample uses the BOOST libraries. BOOST libraries provide a very easy way of managing shared memory objects independent from the underlying operating system.
#include <boost/interprocess/managed_shared_memory.hpp>
#include
using namespace boost::interprocess;
int main()
{
// delete SHM if exists
shared_memory_object::remove("my_shm");
// create a new SHM object and allocate space
managed_shared_memory managed_shm(open_or_create, "my_shm", 1024);
// write into SHM
// Type: int, Name: my_int, Value: 99
int *i = managed_shm.construct("my_int")(99);
std::cout << "Write into shared memory: "<< *i << '\n';
// write into SHM
// Type: std::string, Name: my_string, Value: "Hello World"
std::string *sz = managed_shm.construct("my_string")("Hello World");
std::cout << "Write into shared memory: "<< *sz << '\n' << '\n';
// read INT from SHM
std::pair<int*, std::size_t> pInt = managed_shm.find("my_int");
if (pInt.first) {
std::cout << "Read from shared memory: "<< *pInt.first << '\n';
}
else {
std::cout << "my_int not found" << '\n';
}
// read STRING from SHM
std::pair<std::string*, std::size_t> pString = managed_shm.find("my_string");
if (pString.first) {
std::cout << "Read from shared memory: "<< *pString.first << '\n';
}
else {
std::cout << "my_string not found" << '\n';
}
}