Search code examples
c++boostshared-memoryinterprocess

How to wipe some contents of boost managed_shared_memory?


The boost::interprocess::managed_shared_memory manual and most other resources I checked always shows examples where there is a parent process and a bunch of children spawned by it.

In my case, I have several processes spawned by a third part application and I can only control the "children". It means I cannot have a central brain to allocate and deallocate the shared memory segment. All my processes must be able to do so (Therefore, I can't erase data on exit).

My idea was to open_or_create a segment and, using a lock stored (find_or_construct'ed) in this area, I check a certain hash to see if the memory area was created by this same software version.

If this is not true, the memory segment must be wiped to avoid breaking code.

Ideally, I would want to keep the lock object because there could be other processes already waiting on it.

Things I though:

  1. List all object names and delete all but the lock.

    • This can not be done because the objects might be using different implementations
    • Also I couldn't find where to list the names.
  2. Use shared_memory_object::truncate

    • I could not find much about it
    • By using a managed_shared_memory, I don't know how reliable it would be because I'm not sure the lock was the first allocated data.
  3. Refcount the processes and wipe data on last one

    • Prone to fatal termination problems.
  4. Use a separated shared memory area just for this bookkeeping.

    • Sounds reasonable, but overkill?

Any suggestions or insights?


Solution

  • This sounds like a "shared ownership" scenario.

    What you'd usually think of in such a scenario, would be shared pointers:

    Interprocess has specialized shared pointers (and ditto make_shared) for exactly this purpose.

    Creating the shared memory realm can be done "optimistically" from each participating process (open_or_create). Note that creation needs to be synchronized. Further segment manager operations are usually already implicitly synchronized:

    Whenever the same managed shared memory is accessed from different processes, operations such as creating, finding, and destroying objects are automatically synchronized. If two programs try to create objects with different names in the managed shared memory, the access is serialized accordingly. To execute multiple operations at one time without being interrupted by operations from a different process, use the member function atomic_func() (see Example 33.11).