Add flock based implementation for managed_nonpersistent_shared_memory #132
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Hi Ion,
a few years back we ran into the same problem like many other boost.interprocess users. Posix shared memory / file-backed shared memory semantics make it hard to recover after one of the participating processes has terminated unexpectedly, see
[1] [2] [3] [4] and issues #65 #56 #109
Windows shared memory fixes this by releasing the shared memory object. Linux has robust locks that tell the user that the owner has crashes. Other systems such as macOS have no easy solution.
We have used and tested the attached solution for the last few years on macOS and hope that it is robust. The core of the implementation is
nonpersistent_shared_memory_object::priv_open_or_create
In short, the backing file is first opened with an exclusive lock, which indicates that the caller is the first to open the file. The file is then truncated and the lock is degraded to a shared lock. When obtaining the exclusive lock fails, the caller tries immediately to get a shared lock.
A callback notifies the user if the shared memory was created, not opened and lets the user reinitialize associated objects such as semaphores. See the example in
example/cpp11_nonpersistent_shared_memory.cpp
There are frequently documented problems with flock that don't seem to be a problem here:
Switching from an exclusive lock to a shared lock is not actually atomic. Only two things can happen (see comments in
nonpersistent_shared_memory_object::priv_open_or_create
:flock style locks do not work reliably on NFS file systems. Using shared memory backing files on different computers simultaneously seems to be an accident and not a feature. If the backing file is stored on an NFS drive but only accessed locally (by adding a host identifier to the file name?), NFS
locallocks
seems to be well supported and sufficient.