Boost logo

Boost :

Subject: [boost] [interprocess] leaked named mutexes
From: Eric Niebler (eniebler_at_[hidden])
Date: 2013-03-06 17:51:32


I recently discovered that a process can very easily leave a named mutex
dangling. Consider the following:

#include <cstdlib>
#include <iostream>
#include <boost/interprocess/sync/named_mutex.hpp>
#include <boost/interprocess/sync/scoped_lock.hpp>
namespace ip = boost::interprocess;

char const *name = "mynamedmutex";

int main(int argc, char*argv[])
{
  ip::named_mutex mtx(ip::open_or_create, name);
  std::cout << "acquiring named mutex" << std::endl;
  ip::scoped_lock<ip::named_mutex> lock(mtx);
  std::cout << "acquired" << std::endl;
  exit(EXIT_FAILURE); // whoops
}

On my Linux box, this runs fine the first time, but the second time it
hangs waiting to acquire the mutex. I have to manually delete the
semaphore in /dev/shm/.

This will happen whenever the process exits without calling destructors
of locals; for instance:

- std::exit
- std::quick_exit
- std::abort
- std::terminate
- a crash
- assert failure
- an unhandled exception
- etc..

I find I can handle *some* of this by registering a terminate handler,
an exit handler (and on C++11, a quick_exit handler) that calls
boost::interprocess::named_mutex::remove. This raises a few questions,
though...

- Is there a better way?
- Is it safe to `remove` the same named mutex multiple times?
- Does this clean up only this process's use of the named_mutex, or does
it nuke it from the system, even if another process is using it? (The
docs suggest the latter, which is not what I want, is it?)

Thanks,

-- 
Eric Niebler
Boost.org

Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk