Windows 2012上的CreateMutex,错误代码为ERROR_ACCESS_DENIED

时间:2015-06-08 12:59:52

标签: c++ windows mutex

我正在尝试使用以下代码在Windows 2012上创建互斥锁:

CreateMutex(securityAttributes, FALSE, TEXT("Global\\test"));

它总是给出错误代码5(ERROR_ACCESS_DENIED)。

我尝试创建我发现的here安全属性,但没有成功。 请注意,此代码适用于Windows 7。

这里可能有什么问题?

我想创建可供Windows服务(系统帐户)和用户帐户使用的全局互斥锁。

1 个答案:

答案 0 :(得分:3)

似乎问题是安全属性不合适。它现在有效。以下是用于创建安全属性的代码。

DWORD dwRes;
PSID pEveryoneSID = NULL, pAdminSID = NULL;
PACL pACL = NULL;
PSECURITY_DESCRIPTOR pSD = NULL;
EXPLICIT_ACCESS ea[2];
SID_IDENTIFIER_AUTHORITY SIDAuthWorld = SECURITY_WORLD_SID_AUTHORITY;
SID_IDENTIFIER_AUTHORITY SIDAuthNT = SECURITY_NT_AUTHORITY;
PSECURITY_ATTRIBUTES pSA = NULL;
DWORD resultCode;

if( !AllocateAndInitializeSid( &SIDAuthWorld,  1, SECURITY_WORLD_RID, 0, 0, 0, 0, 0, 0, 0,  &pEveryoneSID ) )
{
    resultCode = -1;
    goto ErrCleanUp;
}

ZeroMemory(&ea, 2 * sizeof(EXPLICIT_ACCESS));
ea[0].grfAccessPermissions  = GENERIC_ALL; 
ea[0].grfAccessMode         = SET_ACCESS;
ea[0].grfInheritance        = NO_INHERITANCE;
ea[0].Trustee.TrusteeForm   = TRUSTEE_IS_SID;
ea[0].Trustee.TrusteeType   = TRUSTEE_IS_WELL_KNOWN_GROUP;
ea[0].Trustee.ptstrName     = (LPTSTR) pEveryoneSID;

if(! AllocateAndInitializeSid( &SIDAuthNT, 
                               2,
                               SECURITY_BUILTIN_DOMAIN_RID,
                               DOMAIN_ALIAS_RID_ADMINS,
                               0, 0, 0, 0, 0, 0,
                               &pAdminSID ) ) 
{
    resultCode = -1;
    goto ErrCleanUp; 
}

ea[1].grfAccessPermissions = GENERIC_ALL; 
ea[1].grfAccessMode        = SET_ACCESS;
ea[1].grfInheritance       = NO_INHERITANCE;
ea[1].Trustee.TrusteeForm  = TRUSTEE_IS_SID;
ea[1].Trustee.TrusteeType  = TRUSTEE_IS_GROUP;
ea[1].Trustee.ptstrName    = (LPTSTR) pAdminSID;

dwRes = SetEntriesInAcl(2, ea, NULL, &pACL);

if (ERROR_SUCCESS != dwRes) 
{
    resultCode = -1;
    goto ErrCleanUp;
}

pSD = (PSECURITY_DESCRIPTOR) LocalAlloc( LPTR, 
                                         SECURITY_DESCRIPTOR_MIN_LENGTH ); 
if (NULL == pSD) 
{ 
    resultCode = -1;
    goto ErrCleanUp; 
} 

if ( !InitializeSecurityDescriptor( pSD,
                                    SECURITY_DESCRIPTOR_REVISION ) ) 
{  
    resultCode = -1;
    goto ErrCleanUp; 
} 

if (! SetSecurityDescriptorDacl( pSD,  TRUE,  pACL, FALSE ) )  
{  
    resultCode = -1;
    goto ErrCleanUp; 
} 

pSA = (PSECURITY_ATTRIBUTES) LocalAlloc(LPTR, sizeof(SECURITY_ATTRIBUTES)); 
if (NULL == pSA) 
{ 
    resultCode = -1;
    goto ErrCleanUp; 
} 

ZeroMemory(pSA, sizeof(SECURITY_ATTRIBUTES));
pSA->nLength = sizeof(SECURITY_ATTRIBUTES);
pSA->lpSecurityDescriptor = pSD;
pSA->bInheritHandle = FALSE;

*ppsa = pSA;

return 0;

ErrCleanUp:

if (pEveryoneSID) 
    FreeSid(pEveryoneSID);
if (pAdminSID) 
    FreeSid(pAdminSID);
if (pACL) 
    LocalFree(pACL);
if (pSD) 
    LocalFree(pSD);
if (pSA) 
    LocalFree(pSA);

*ppsa = NULL;
return 0;