3

I'm using boost::interprocess to share data between processes via managed shared memory. Clients may read or write to the shared memory.

Clients first attempt to open an existing shared memory:

managed_shared_memory(open_only, "MySharedMemory");

If the open fails then the memory is created:

managed_shared_memory(create_only, "MySharedMemory");

Once the shared memory has been opened or created the client increments the client count (integer stored in the shared memory).

When a client's destructor is called the client count is decremented. If client count == 0 then the shared memory is removed:

shared_memory_object::remove("MySharedMemory");

So far so good. However, if a process crashes then it can't decrement the client count so the memory isn't properly removed.

At this point a new client may successfully open the shared memory in whatever state it was left in instead of a fresh default state. This is problematic.

So my question is. What is the best way to manage the lifetime of shared memory?

Not crashing is a good idea but I'm working in a plugin environment where something beyond my control could take everything down and clients come and go continuously.

Another idea is to use pipes or sockets to verify that clients are still valid (e.g. ping them when the memory is opened and cleanup manually if there is no response) but this feels like overkill.

Stephen Blinkhorn
  • 637
  • 2
  • 7
  • 17
  • Are you targeting Windows, Linux, or both? – Mark Waterman Apr 29 '17 at 01:00
  • 1
    Oops, nevermind, I see from your profile that you're probably working on a Mac OS X app. (If you were on Windows then I was going to suggest using [managed_windows_shared_memory](http://www.boost.org/doc/libs/1_64_0/doc/html/interprocess/managed_memory_segments.html#interprocess.managed_memory_segments.managed_shared_memory.windows_managed_memory_common_shm), which does cleanup for you in the event of a crash). – Mark Waterman Apr 29 '17 at 01:09
  • Targeting OS X and Windows so can't take advantage of managed_windows_shared_memory unfortunately. – Stephen Blinkhorn Apr 29 '17 at 01:20
  • Assuming your application has the possibility of crashing randomly, I believe this problem is unlikely to be solved in user space. Which unfortunately means platform specific :( – Passer By Apr 29 '17 at 02:35
  • 1
    You can try *tracking* references instead of counting them. The tracked references will stay in the shared memory beyond its lifetime only if it crashed. Stuff some code that sweeps through the references and cleanup. – Passer By Apr 29 '17 at 02:39

0 Answers0