I've the following code...
On one machine it throws ERROR_ACCESS_DENIED and on other it throws ERROR_ALREADY_EXISTS (Handle is not NULL). I'd like to understand why two different behaviors. On both the machines user is a domain user part of local system administrators group. I tried running three instances simultaneously.
#include <windows.h>
#include<iostream>
using namespace std;
void * _hMutex = NULL;
void createMyMutex()
{
_hMutex = CreateMutex(
NULL, // default security attributes
false, // initially not owned
L"LockTest"); // named mutex
if (_hMutex == NULL)
{
cout<< GetLastError()<< " Error creating mutex handle"<<endl;
Exit(0);
}
if(GetLastError() == ERROR_ALREADY_EXISTS)
{
cout<< GetLastError()<< " Mutex already created" <<endl;
}
}
void Lock()
{
cout<<"Acquiring Lock..."<< endl;
if(_hMutex != NULL)
WaitForSingleObject(_hMutex, INFINITE);
cout<< "Acquired Lock." <<endl;
}
void Unlock()
{
cout<< "Releasing Lock..." <<endl;
if(_hMutex != NULL)
ReleaseMutex(_hMutex);
}
int main(int argc, char* argv[])
{
cout<<"Creating lock"<<endl;
createMyMutex();
cout<<"Lock create success"<<endl;
cout<<"Taking lock"<<endl;
Lock();
cout<<"Got the lock"<<endl;
cout<<"Waiting for 20 seconds"<<endl;
Sleep(20000);
cout<<"Wait over"<<endl;
cout<<"Releasing lock"<<endl;
Unlock();
cout<<"Lock released successfully"<<endl;
cout<<"exiting the program"<<endl;
return 0;
}