c00*_*0fd 3 c++ windows winapi synchronization mutex
我需要使用全局互斥锁来同步多个进程对相互共享文件的访问。我这样创建互斥锁:
HANDLE hMutex = ::CreateMutex(NULL, FALSE, L"Global\\MySpecialName");
Run Code Online (Sandbox Code Playgroud)
然后在:
//Entering critical section
VERIFY(::WaitForSingleObject(hMutex, INFINITE) == WAIT_OBJECT_0);
Run Code Online (Sandbox Code Playgroud)
进而:
//Leave critical section
VERIFY(::ReleaseMutex(hMutex));
Run Code Online (Sandbox Code Playgroud)
该问题源于以下事实:共享此互斥锁的进程是本地系统服务和几个使用登录用户凭据运行的用户模式进程。因此,如果互斥锁首先由服务创建,那么当用户模式进程尝试打开它时,会CreateMutex失败并显示错误代码ERROR_ACCESS_DENIED。
在创建互斥锁之前,我正在阅读为它指定一个安全描述符,但我似乎无法弄清楚如何使其可访问everything,我在这里真的不需要任何复杂性?
这是我使用的,基于这篇文章:
HANDLE hMutex = NULL;
DWORD dwError;
// Create a global mutex
pSecDesc = MakeAllowAllSecurityDescriptor();
if(pSecDesc)
{
SECURITY_ATTRIBUTES SecAttr;
SecAttr.nLength = sizeof(SECURITY_ATTRIBUTES);
SecAttr.lpSecurityDescriptor = pSecDesc;
SecAttr.bInheritHandle = FALSE;
hMutex = CreateMutex(&SecAttr, TRUE, MUTEX_NAME);
dwError = GetLastError();
LocalFree(pSecDesc);
}
Run Code Online (Sandbox Code Playgroud)
...
//
// From http://blogs.msdn.com/b/winsdk/archive/2009/11/10/access-denied-on-a-mutex.aspx
//
PSECURITY_DESCRIPTOR MakeAllowAllSecurityDescriptor(void)
{
WCHAR *pszStringSecurityDescriptor;
if(GetWindowsVersion(NULL) >= 6)
pszStringSecurityDescriptor = L"D:(A;;GA;;;WD)(A;;GA;;;AN)S:(ML;;NW;;;ME)";
else
pszStringSecurityDescriptor = L"D:(A;;GA;;;WD)(A;;GA;;;AN)";
PSECURITY_DESCRIPTOR pSecDesc;
if(!ConvertStringSecurityDescriptorToSecurityDescriptor(pszStringSecurityDescriptor, SDDL_REVISION_1, &pSecDesc, NULL))
return NULL;
return pSecDesc;
}
Run Code Online (Sandbox Code Playgroud)