I tend to use boost::interprocess::named_mutex for the same thing. The equivalent code is something like:
using boost::interprocess;
const char *application_name = "Application Name";
int main()
try
{
struct named_mutex_killer
{
~named_mutex_killer() { named_mutex::remove( application_name ); }
}killer;
named_mutex instance_lock( create_only, application_name );
std::cout << "Only instance of application started..." << std::endl;
}
catch( interprocess_exception &e )
{
std::cout << "Running second instance of application" << std::endl;
}
It also works on FreeBSD and Linux (at least the versions I've tried) if that sort of thing's important to you.
It's slightly annoying that you have to use an auxillary structure to clean up the mutex. ~named_mutex() doesn't remove the underlying system mutex, it just makes sure that the mutex with the name is unlocked.
And to amplify the original author's point you can do it with any shared resource between processes - semaphores, file locks, you name it, not just mutexes although on pthread systems they tend to be the most primitive.
Cheers,
Ash