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")
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)
{
InterlockedDecrement(&gs_nCtApp)
MessageBox(NULL, _T("One Instance Is Already Running."), _T("Information"), 0);
return 0;
}
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...