我需要知道当前进程是否正在作为系统运行。在C#中,我使用WindowsIdentity.GetCurrent().IsSystem做到这一点,C++中的等效功能是什么?

我试图避免比较用户名,因为不同的操作系统对SYSTEM帐户具有不同的用户名。

最佳答案

我基于Eryk的想法创建了一个示例,它的工作原理是:

BOOL IsSystem()
{
    HANDLE hToken = NULL;
    BOOL result = false;
    TOKEN_USER *tokenUser = NULL;
    DWORD dwLength = 0;

    if (OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &hToken) == 0)
    {
        DbgPrint("OpenProcessToken(): %d", GetLastError());
        goto cleanup;
    }

    if (GetTokenInformation(hToken, TokenUser, (LPVOID) tokenUser, 0, &dwLength) == 0)
    {
        if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
        {
            DbgPrint("GetTokenInformation(): %d", GetLastError());
            goto cleanup;
        }

        tokenUser = (TOKEN_USER *) HeapAlloc(GetProcessHeap(), HEAP_ZERO_MEMORY, dwLength);
        if (tokenUser == NULL)
        {
            goto cleanup;
        }

        if (GetTokenInformation(hToken, TokenUser, (LPVOID) tokenUser, dwLength, &dwLength) == 0)
        {
            DbgPrint("GetTokenInformation(): %d", GetLastError());
            goto cleanup;
        }

        result = IsWellKnownSid(tokenUser->User.Sid, WinLocalSystemSid);
    }

cleanup:
    if (tokenUser != NULL)
    {
        HeapFree(GetProcessHeap(), NULL, tokenUser);
    }

    return result;
}

10-08 11:50