Single instance console app?

Started by andre104, March 13, 2011, 04:29:47 PM

Previous topic - Next topic

andre104

How to make a single instance console app?
I found this, unfortunately it uses FindWindow(), which is not appropriate for console apps, right?

Stefan Pendl

Register a Mutex.

You will find information at MSDN and by searching the web.
---
Stefan

Proud member of the UltraDefrag Development Team

TimoVJL

#2
Try this:
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#include <stdio.h>

TCHAR szMutex[] = "Global\\{6EBCEE90-C5EB-4891-A818-D7ED72F3AE3A}";

int main(int argc, char **argv)
{
// Try to open the mutex.
//HANDLE hMutex = OpenMutex(MUTEX_ALL_ACCESS, 0, szMutex);
HANDLE hMutex = OpenMutex(SYNCHRONIZE, 0, szMutex);
if (hMutex) {
printf("Already running %Xh %d\n", (int)hMutex, GetLastError());
return 0;
}
hMutex = CreateMutex(0, 0, szMutex);
// ***************
printf("First run %Xh\npress enter to stop \n", (int)hMutex);
getchar();
// ***************
ReleaseMutex(hMutex);
CloseHandle(hMutex);
return 0;
}

May the source be with you

CommonTater

another very similar way of doing the first run mutex is this....

// Test if first copy.
CreateMutex(NULL,1,L"MY_NIFTY_MUTEX_NAME");
if (GetLastError() == ERROR_ALREADY_EXISTS)
  return 0;