Click here to Skip to main content
15,891,529 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.
5.00/5 (2 votes)
3 Feb 2011CPOL 6K   1  
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.

C#
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)


Written By
Software Developer Aloatec
France France
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --