#include <boost/interprocess/shared_memory_object.hpp>#include <boost/interprocess/file_mapping.hpp>#include <boost/interprocess/mapped_region.hpp>#include <iostream>namespace bip = boost::interprocess;struct test_obj { size_t x; size_t y; uint8_t buf[32]; bool is_valid;};#ifdef COLIRU #include <fstream> using mapping_type = bip::file_mapping;#else using mapping_type = bip::shared_memory_object;#endiftemplate <typename T>class shm_wrapper { static_assert(std::is_trivial_v<T>); static_assert(std::is_standard_layout_v<T>);#ifdef COLIRU // file mappings require more work to cater for the storage struct backing_t { } backing; backing_t ensure_file(std::string name, size_t size) { std::filebuf fbuf; fbuf.open(name, std::ios::in | std::ios::out | std::ios::app | std::ios::binary); //set the size, sparsely fbuf.pubseekoff(size-1, std::ios_base::beg); fbuf.sputc(0); fbuf.close(); return {}; } public: shm_wrapper() : backing { ensure_file("my_shm", sizeof(T)) }, m_mappable("my_shm", bip::read_write), m_reg(m_mappable, bip::read_write, 0, sizeof(T)) { }#else public: shm_wrapper() : m_mappable(bip::open_or_create, "my_shm", bip::read_write), m_reg(m_mappable, bip::read_write, 0, sizeof(T)) { m_mappable.truncate(sizeof(T)); }#endif T& get() { return *static_cast<T*>(m_reg.get_address()); } T const& get() const { return *static_cast<T const*>(m_reg.get_address()); } auto size() const { return m_reg.get_size(); } auto flush() { return m_reg.flush(); } private: mapping_type m_mappable; bip::mapped_region m_reg;};int main() { shm_wrapper<test_obj> w; std::cout << "x:" << w.get().x << "\n"; w.get().x ^= 0xa7; return w.flush()? 0 : 1;}连续运行4倍时打印:x:0x:167x:0x:167 这篇关于为什么boost :: interprocess :: managed_shared_memory在构造时会抛出boost :: interprocess_exception?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 上岸,阿里云!
08-28 06:15