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

Tagged as

Go to top

How to avoid multiple instances of your Windows application

, 3 Feb 2011
Rate this:
Please Sign up or sign in to vote.
This solution works in Windows environment under Visual Studio.I don't know if there is a Linux equivalent.I use a counter common for all processes.#pragma data_seg("counter") // counter common for all processesLONG gs_nCtApp = -1; #pragma data_seg()#pragma comment(linker,...
This solution works in Windows environment under Visual Studio.
I don't know if there is a Linux equivalent.
 
I use a counter common for all processes.
 
#pragma data_seg("counter") 
// counter common for all processes
LONG gs_nCtApp = -1; 
#pragma data_seg()
#pragma comment(linker, "/section:counter,rws") 
 
Each time the program enter in main(), it checks the counter.
If its value is greater than 0, then another process is running.
Else, the counter is incremented.
 
int main()
{
    bool bFirstInstance =  (InterlockedIncrement(&gs_nCtApp) == 0);
    if (!bFirstInstance)
    {
       // tell the user another process is running
       InterlockedDecrement(&gs_nCtApp)
       MessageBox(NULL, _T("One Instance Is Already Running."), _T("Information"), 0);
       return 0;
    }
    // do processing
    // ...

    // no need to decrement
    return 0;
}
 
There is no need to decrement at the end of the first process because when it will end, the image will be unloaded from memory.
So the next time it will be launched, it will be reset.
 
Note: This solution is not from me, but I can't remember where I saw it. Sorry to the author...

License

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

Share

About the Author

Menuki
Software Developer Aloatec
France France
No Biography provided

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web04 | 2.8.140916.1 | Last Updated 3 Feb 2011
Article Copyright 2011 by Menuki
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid