Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / Win32

How to avoid multiple instances of your Windows application

4.40/5 (5 votes)
27 Sep 2010CPOL 11.6K  
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() {...
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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)