Single instance C application using a Mutex object

We need three functions:

OpenMutex function
Opens an existing named mutex object.

CreateMutex function
Creates or opens a named or unnamed mutex object.

ReleaseMutex function
Releases ownership of the specified mutex object.

#include <stdlib.h>
#include <stdio.h>
#include <windows.h>
 
int main(void)
{
      HANDLE hMutex = OpenMutex(MUTEX_ALL_ACCESS, 0, "MyApp");
      if (!hMutex){
        hMutex = CreateMutex(0, 0, "MyApp");
	if(!hMutex){
	    perror("Unable to create Mutex object:");
	    return 0;
	}
      }
      else {
	    printf("Application already running\n");
	    return 0;
      }
 
      //release mutex object when exiting-closing application
      //ReleaseMutex(hMutex);
 
      //for testing purposes - to keep application running
      WaitForSingleObject(GetCurrentProcess(), INFINITE);
      return EXIT_SUCCESS;
}
Categories: C, Programming Tags: , ,
%d bloggers like this: