Remove posix shared memory when not in use?

If there is a point in your program's execution when it is well known, that all processes that need to open the shared memory segment have already done so, you can safely unlink it. Unlinking removes the object from the global namespace but it sill lingers around as long as there is at least one process that keep its file descriptor open. If a crash occurs after that point, the file descriptor is automatically closed and the reference count is decremented. Once no open descriptors to the unlinked shared memory block remain, it is deleted.

This is useful in the following scenario: a process creates a shared memory block, unlinks it and then forks. The child inherits the file descriptor and can use the shared memory block to communicate with the parent. Once both processes terminate, the block is automatically removed as both file descriptors get closed.

While unlinked, the shared memory block is unavailable for other processes to open it. Meanwhile, if one use shm_open() with the same name as the unlinked block, a new and completely different shared memory block would be created instead.


I found a way using a system command and the Linux command "fuser" which allow to list the processes which opened a file. This way, you can check if the shared memory file (located in /dev/shm") is still in use and delete it if not. Note that the operations of check / delete / create must be enclosed in a inter-processes critical section using a named mutex or named semaphore or file lock.

        std::string shm_file = "/dev/shm/" + service_name + "Shm";
        std::string cmd_line = "if [ -f " + shm_file + " ] ; then if ! fuser -s " + shm_file + " ; then rm -f " + shm_file + " ; else exit 2 ; fi else exit 3 ; fi";
        int res = system(cmd_line.c_str());
        switch (WEXITSTATUS(res)) {
        case 0: _logger.warning ("The shared memory file " + shm_file + " was found orphan and is deleted");         break;
        case 1: _logger.critical("The shared memory file " + shm_file + " was found orphan and cannot be deleted");  break;
        case 2: _logger.trace   ("The shared memory file " + shm_file + " is linked to alive processes");            break;
        case 3: _logger.trace   ("The shared memory file " + shm_file + " is not found");                            break;
        }

No - at lest on Linux, the kernel doesn't contain anything that can do this. It's up to some application to call shm_unlink() at some point to get rid of a shared memory segment.