Use shared library destructor to remove shared memory if not used anymore
===

I have a C++ shared library (Windows+Mac) that manages a shared memory with boost::interprocess::shared_memory_object.

This library is used by 2 processes.
The shared memory is set up in the constructor of the DLL for use by its functions.

something like this (shortened):

    static shared_memory_object * FGEDLinkMemory;
    static mapped_region * FGEDMappedRegion;

    #ifdef __GNUC__
    __attribute__((constructor))
    #endif
    void initializer(){
        static shared_memory_object shm(open_only, "FGEDLinkMemory", read_write);
        FGEDLinkMemory = &shm;
        // If open_only fails, create a new one
        ...
        // create a mapped_region and link it to FGEDMappedRegion
        // set up pointers to specific offsets in the mapped region
        ...
    }

I can then use _FGEDLinkMemory_ and _FGEDMappedRegion_ throughout the library.

__Now my problem__:

I must not remove the shared memory until both processes are detached from it.
At first, I used QSharedMemory (Qt libraries), which was very convenient, as it was automatically removed, once all processes detached from it - with boost this is no longer true. The memory stays persistent (at least on OS X where I currently test it).

In fact, I consider boost's implementation actually dangerous, as I can remove the shared memory, and all other processes attached to it secretly get a new name for their 'instance' of shared memory.  

Now since I want to remove the shared memory once all processes are detached, I figured, I write a counter into shared memory, that gets increased by each DLL instance that attaches to it, and decreased whenever a DLLs destructor is called.

Problem is, that I cannot do this in a destructor of a DLL it seems.
When I try to access the shared memory, I get segmentation faults, and locking my mutex for accessing the shared memory is out of the question anyway (destructors must not lock afaik).
I am not quite sure why I can't access my shared memory anymore, as my global static variables  are still accessible in the destructor and I don't know why the pointers to the shared memory are invalid. (I set up pointers to within my mapped_region in the constructor to access specific elements, and using them segfaults)

__What I would like__:

 - When both processes detach from the shared memory, it should be deleted.
 - When one process detaches, it should later be able to reattach to the same shared memory.
 - Must work on Mac and Windows


Is there a way of doing this with boost::interprocess::shared_memory_object?
Am I thinking too complicated?
I have searched everywhere but couldn't find a solution.

Any help appreciated!
Thomas