Click here to Skip to main content
Click here to Skip to main content
Alternative Tip/Trick

Tagged as

How to avoid multiple instances of your Windows application

, 27 Sep 2010 CPOL
Rate this:
Please Sign up or sign in to vote.
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()
    struct named_mutex_killer
        ~named_mutex_killer() { named_mutex::remove( application_name ); }
    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.


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


About the Author

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.
Follow on   Google+

Comments and Discussions

GeneralMy vote of 2 PinmemberChris Hills26-Nov-13 7:51 
GeneralRe: My vote of 2 [modified] PinmemberAescleal26-Nov-13 8:11 
GeneralRe: My vote of 2 PinmemberChris Hills27-Nov-13 0:13 
GeneralRe: My vote of 2 PinmemberAescleal27-Nov-13 1:03 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150123.1 | Last Updated 27 Sep 2010
Article Copyright 2010 by Aescleal
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid