Named Mutex
A C program that creates a named mutex and uses GetLastError to detect whether another process already holds it.
The standard single-instance / cross-process lock pattern. CreateMutex with a name never actually fails when the name is already taken - it hands you a handle to the existing mutex and sets GetLastError to ERROR_ALREADY_EXISTS, which is exactly what this snippet checks to tell "I created it" from "someone else already has it." That two-state result is the whole trick behind "only one instance can run" dialogs and simple inter-process critical sections.
#include <windows.h>
#include <stdio.h>
#include <conio.h>
int main()
{
LONG LastError;
HANDLE hMutex;
hMutex = CreateMutex(0, FALSE, "MyMutex");
LastError = GetLastError();
if(hMutex != 0)
{
if(LastError == ERROR_SUCCESS)
printf("%s\n", "Mutex creation succeeded.");
if(LastError == ERROR_ALREADY_EXISTS)
printf("%s\n", "Mutex already exists.");
}
else printf("%s\n", "Mutex creation failed.");
ReleaseMutex(hMutex);
CloseHandle(hMutex);
return TRUE;
}
Note the call is made non-abandoned (FALSE) so the first caller owns the mutex; in a real single-instance app you would keep the handle open for the life of the process and simply exit when ERROR_ALREADY_EXISTS comes back.