我需要使用全局互斥来同步多个进程对共享文件的访问。 我创build这个互斥体:
HANDLE hMutex = ::CreateMutex(NULL, FALSE, L"Global\\MySpecialName");
然后用于:
//Entering critical section VERIFY(::WaitForSingleObject(hMutex, INFINITE) == WAIT_OBJECT_0);
接着:
//Leave critical section VERIFY(::ReleaseMutex(hMutex));
这个问题是由于共享这个互斥体的进程是一个本地系统服务以及几个用login用户的凭证运行的用户模式进程而引起的。 因此,如果互斥体是由服务首先创build的,那么当用户模式进程尝试打开它时, CreateMutex
失败,错误代码为ERROR_ACCESS_DENIED
。
在创build之前,我正在阅读指定互斥锁的安全描述符,但是我似乎无法弄清楚如何使其可以被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); }
…
// // 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; }