代码来自 Windows 核心编程。简单修改测试通过(win10)。可能需要管理员权限。提权代码这里没写。
本文只是一个简单示例。
do
{
wchar_t* _namespace = L"TestNamespace";
wchar_t* _mutexName = L"mutexName";
wchar_t* _boundName = L"TestBoundName";
HANDLE hd_BoundaryDscrpt = CreateBoundaryDescriptorW(_boundName, 0);
BYTE localAdminSID[SECURITY_MAX_SID_SIZE] = { 0 };
PSID pLocalAdminSID = &localAdminSID;
DWORD cbSID = sizeof(localAdminSID);
if (!CreateWellKnownSid(WinBuiltinAdministratorsSid, NULL, pLocalAdminSID, &cbSID))
{
std::cout << "Call error 1" << std::endl;
break;
}
if (!AddSIDToBoundaryDescriptor(&hd_BoundaryDscrpt, pLocalAdminSID))
{
std::cout << "Call error 2" << std::endl;
break;
}
SECURITY_ATTRIBUTES sa = { 0 };
sa.nLength = sizeof(sa);
sa.bInheritHandle = FALSE;
if (!ConvertStringSecurityDescriptorToSecurityDescriptorW(TEXT("D:(A;;GA;;;BA)"), SDDL_REVISION_1, &sa.lpSecurityDescriptor, NULL))
{
std::cout << "Call error3 " << std::endl;
break;
}
HANDLE hd_namespace = CreatePrivateNamespaceW(&sa, hd_BoundaryDscrpt, L"TestNamespace");
LocalFree(sa.lpSecurityDescriptor);
if (NULL == hd_namespace)
{
int err = GetLastError();
if (err = ERROR_ACCESS_DENIED)
{
break;
}
else if (err = ERROR_ALREADY_EXISTS)
{
hd_namespace = OpenPrivateNamespaceW(hd_BoundaryDscrpt, _namespace);
}
}
if (NULL == hd_namespace)
{
std::cout << "Call error 4" << std::endl;
break;
}
wchar_t mutexName[256] = { 0 };
wsprintf(mutexName, L"%s\\%s", _namespace, _mutexName);
HANDLE hd_mutex = CreateMutexW(NULL, FALSE, mutexName);
if (NULL == hd_mutex)
{
int err = GetLastError();
if (err == ERROR_ALREADY_EXISTS)
{
break;
}
}
DeleteBoundaryDescriptor(hd_BoundaryDscrpt);
} while (0);