我有以下代码...
在一台机器上它抛出 ERROR_ACCESS_DENIED 而在另一台机器上它抛出 ERROR_ALREADY_EXISTS (句柄不是 NULL)。我想了解为什么有两种不同的行为。在这两台机器上,用户都是本地系统管理员组的域用户。我尝试同时运行三个实例。
#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;
}