MuteX | How to create a single instance application in C


#include <windows.h>
#include <stdio.h>

#define MUTEX_NAME "mutex name here, anyname"
int main()
{
 HANDLE hMutex = OpenMutex(MUTEX_ALL_ACCESS, FALSE, MUTEX_NAME);
 if(hMutex == NULL)
 {
 // no duplicate instances found
 hMutex = CreateMutex(NULL, FALSE, MUTEX_NAME);
 }
 else
 {
 // a duplicate was found
 return 0;
 }

 printf("Created console\n");
 getchar();
 return 1;
}

As you can see, there’s OpenMuteX and CreateMuteX function that has been used.  To briefly explain this, OpenMuteX opens a handle to check whether a mutex has been created.  If it returns the value NULL, it means that no mutex of the current string has been created.  So when it is NULL, CreateMuteX is called to create the mutex with the string MUTEX_NAME that has been defined.  Leave a feedback if you feel that there’s lack of information.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: