Boost库之共享内存报了异常,怎么解决?
我的本意是想创建一块2M的共享内存,然后往里面写入数据,可以报了boost::interprocess_exception::library_error的异常,不知道如何解决,请大家帮我看看。程序代码:
#include <boost/interprocess/managed_shared_memory.hpp> #include <boost/interprocess/allocators/allocator.hpp> #include <boost/interprocess/containers/vector.hpp> #include <boost/interprocess/sync/named_mutex.hpp> #include <iostream> #define SHM_SIZE 2*1024*1024 typedef boost::interprocess::allocator<int,boost::interprocess::managed_shared_memory::segment_manager> ShmemAllocator; typedef boost::interprocess::vector<int,ShmemAllocator> MyVector; class CShm { public: CShm(); ~CShm(); void Task(void); private: boost::interprocess::named_mutex mutex; MyVector *pObj; }; CShm::CShm():mutex(boost::interprocess::open_or_create,"shm_mtx") { try { boost::interprocess::managed_shared_memory segment(boost::interprocess::open_or_create,"SHM",SHM_SIZE); const ShmemAllocator alloc_inst(segment.get_segment_manager()); MyVector *pObj = segment.construct<MyVector>("MyVector")(alloc_inst); } catch (boost::interprocess::interprocess_exception& ex) { std::cout<<ex.what()<<std::endl; } } CShm::~CShm() { mutex.remove("shm_mtx"); boost::interprocess::shared_memory_object::remove("SHM"); } void CShm::Task(void) { for (int i = 0;i < 10; i++) { mutex.lock(); pObj->push_back(i+1); mutex.unlock(); } mutex.lock(); for (MyVector::const_iterator it = pObj->begin(); it != pObj->end(); it++) std::cout<<*it<<" "; mutex.unlock(); } int main() { CShm _gShm; _gShm.Task(); return 0; }