简体   繁体   中英

how to get process handle from process id?

I have process Id , I want to get its process handle.

Is there any API available for that.

I tried to use OpenProcess but it returns NULL, and GetLastError =0.

This I am trying on Vista.

I guess I need to enable SeDebugPrivilege before using OpenProcess . But for enabling SeDebugPrivilege I need to get its Process handle.

OpenProcess(PROCESS_ALL_ACCESS, TRUE, procId);

您需要验证您是否使用了有效的进程ID,并且您是否被允许从该进程请求的访问权限。

Is this what you are looking for?

HANDLE processHandle = OpenProcess(PROCESS_ALL_ACCESS, FALSE, processId);
CloseHandle(processHandle); 

Also, here is some code I use to set debug privledge before injecting DLLs.

void Loader::EnableDebugPriv(void)
{
    HANDLE              hToken;
    LUID                SeDebugNameValue;
    TOKEN_PRIVILEGES    TokenPrivileges;

    if(OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &hToken))
    {
        if(LookupPrivilegeValue(NULL, SE_DEBUG_NAME, &SeDebugNameValue))
        {
            TokenPrivileges.PrivilegeCount              = 1;
            TokenPrivileges.Privileges[0].Luid          = SeDebugNameValue;
            TokenPrivileges.Privileges[0].Attributes    = SE_PRIVILEGE_ENABLED;

            if(AdjustTokenPrivileges(hToken, FALSE, &TokenPrivileges, sizeof(TOKEN_PRIVILEGES), NULL, NULL))
            {
                CloseHandle(hToken);
            }
            else
            {
                CloseHandle(hToken);
                throw std::exception("Couldn't adjust token privileges!");              
            }
        }
        else
        {
            CloseHandle(hToken);
            throw std::exception("Couldn't look up privilege value!");
        }
    }
    else
    {
        throw std::exception("Couldn't open process token!");
    }
}

I've used the above code on Windows Vista with success.

I just had the exact same issue as described: OpenProcess() == NULL and GetLastError() == 0. Turned out to be the Common Language RunTime Support setting, was set to "Pure" should have been just "Common". Took me ages to find.

For VS2010 c++ goto -> Project Properties -> Configuration Properties -> C/C++ -> General

You would need elevated privileges. Also look at similar question here .

If you have a process identifier, you can get the process handle by calling the OpenProcess function. OpenProcess enables you to specify the handle's access rights and whether it can be inherited.

FYI:
http://msdn.microsoft.com/en-us/library/windows/desktop/ms684868(v=vs.85).aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM