Click here to Skip to main content
15,796,025 members
Articles / Desktop Programming / Win32
Alternative
Tip/Trick

How to avoid multiple instances of your Windows application

Rate me:
Please Sign up or sign in to vote.
4.40/5 (5 votes)
27 Sep 2010CPOL 10.8K   1   4
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)


Written By
Software Developer (Senior)
United Kingdom United Kingdom
I've been programming since 1985 - starting with Fortran 77, then moving onto assembler, C and C++ in about 1991. I also know enough Java and Python to read code but you probably wouldn't want me writing it.

I've worked in a wide variety of application areas - defense, banking, games and security with the longest stints being in security. I also seem to end up programming devices far too often. This time I'm programming terahertz band body scanners.

Comments and Discussions

 
GeneralMy vote of 2 Pin
Chris Hills26-Nov-13 7:51
Chris Hills26-Nov-13 7:51 
Doesn't compile
GeneralRe: My vote of 2 Pin
Aescleal26-Nov-13 8:11
Aescleal26-Nov-13 8:11 
GeneralRe: My vote of 2 Pin
Chris Hills27-Nov-13 0:13
Chris Hills27-Nov-13 0:13 
GeneralRe: My vote of 2 Pin
Aescleal27-Nov-13 1:03
Aescleal27-Nov-13 1:03 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.