views:

491

answers:

3

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.

+2  A: 
OpenProcess(PROCESS_ALL_ACCESS, TRUE, procId);

You'll need to verify that you're using a valid process ID, and that you're permitted the access rights you request from the process.

Matt Joiner
procId is valid.
Alien01
Don't ask for PROCESS_ALL_ACCESS, you're unlikely to get that on a secured install. Only ask for what you need.
Hans Passant
Right, try asking for SYNCHRONIZE, which will almost never fail. Then step up the requested permission from there.
Ben Voigt
+2  A: 

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.

Paperino
This will return Window Handle , not Process HandleI am looking for Process Handle from Process ID
Alien01
As Matt Joiner already said... see above.
Paperino
+1  A: 

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

Igor