简体   繁体   English

跨进程内存管理

[英]Cross process memory managment

I wish to allocate data on a shared memory segment in one process and free it in another. 我希望在一个过程中在共享内存段上分配数据,并在另一个过程中释放它。

I allocate it in process 1 (Proc1) using the following line: new_Class* pData = managed_windows_shared_memory_segment.construct<new_Class>(anonymous_instance) () 我使用以下行在进程1(Proc1)中分配它: new_Class* pData = managed_windows_shared_memory_segment.construct<new_Class>(anonymous_instance) ()

I then convert the pointer to a handle get_handle_from_address(pData) , transfer it to the other process (Proc2) convert it back to a pointer static_cast<new_Class*>managed_windows_shared_memory_segment.get_address_from_handle(handle) and try to deallocate it there. 然后,我将指针转换为句柄get_handle_from_address(pData) ,将其转移到另一个进程(Proc2),将其转换回指针static_cast<new_Class*>managed_windows_shared_memory_segment.get_address_from_handle(handle)并尝试在其中进行分配。 (after Proc1 died i might add) (在Proc1死后,我可能会添加)

when i try to deallocate it in proc 2 with destroy_ptr(pData) I get annoying an annoying exception: "Unhandled exception at 0x0000000000000000" and trying to use deallocate(pData) doesn't fare better. 当我尝试在proc 2中使用destroy_ptr(pData)对其进行分配时,我会遇到一个令人烦恼的异常:“未处理的异常,位于0x0000000000000000”,尝试使用deallocate(pData)不会更好。

when i deallocate from Proc1 all is well, it's just the deallocation from from Proc2 that appears problematic. 当我从Proc1取消分配时一切正常,只是从Proc2进行的重新分配似乎有问题。

Any Ideas? 有任何想法吗?


The problem was caused by a virtual destructor in a base class. 该问题是由基类中的虚拟析构函数引起的。 note to self: Don't use virtual functions on shared memory, the Virtual method table is NOT cross process. 自我注意:不要在共享内存上使用虚拟函数,虚拟方法表不会跨进程。

I would like to thank Chad. 我要感谢乍得。 He rightly pointed out that i should post relevant code which caused me to take a closer look at an obscure base class. 他正确地指出,我应该发布相关的代码,这使我不得不仔细研究一个晦涩难懂的基类。

I heartily suggest using smart pointers, as you would with non-interprocess allocations. 我衷心建议使用智能指针,就像使用非进程间分配一样。

Of course, regular shared_ptr doesn't cut it unless the refcount/weakref are also allocated in the shared memory segment. 当然,除非在共享内存段中也分配了refcount / weakref,否则常规shared_ptr不会削减它。

Luckily, Boost Interprocess comes fully charged with 幸运的是,Boost Interprocess可以完全使用

  • boost::interprocess::shared_ptr<T>
  • boost::interprocess::make_shared<T>(...)

See http://www.boost.org/doc/libs/1_58_0/doc/html/interprocess/interprocess_smart_ptr.html#interprocess.interprocess_smart_ptr.shared_ptr 参见http://www.boost.org/doc/libs/1_58_0/doc/html/interprocess/interprocess_smart_ptr.html#interprocess.interprocess_smart_ptr.shared_ptr

There are also scoped_ptr<> , unique_ptr<> and even an intrusive_ptr<> for all your peculiar needs :) 也有scoped_ptr<>unique_ptr<>甚至是intrusive_ptr<>可以满足您所有特殊的需求:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM