cwindowswinapiprocess

Get Parent Process Name (Windows)


I am trying to get the name of the parent process (full path) in a Windows Console application (C/C++). It looks like it should work, but it is failing and I can't see what I am doing wrong. It is successfully getting the parent PID, but failing on getting the name. Any corrections would be appreciated.

#include <Windows.h>
#include <stdio.h>
#include <tlhelp32.h>
#include <Psapi.h>

DWORD getParentPID(DWORD pid)
{
    HANDLE h = NULL;
    PROCESSENTRY32 pe = { 0 };
    DWORD ppid = 0;
    pe.dwSize = sizeof(PROCESSENTRY32);
    h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
    if( Process32First(h, &pe)) 
    {
        do 
        {
            if (pe.th32ProcessID == pid) 
            {
                ppid = pe.th32ParentProcessID;
                break;
            }
        } while( Process32Next(h, &pe));
    }
    CloseHandle(h);
    return (ppid);
}

int getProcessName(DWORD pid, PUCHAR fname, DWORD sz)
{
    HANDLE h = NULL;
    int e = 0;
    h = OpenProcess
    (
        PROCESS_QUERY_INFORMATION,
        FALSE,
        pid
    );
    if (h) 
    {
        if (GetModuleFileNameEx(h, NULL, fname, sz) == 0)
            e = GetLastError();
        CloseHandle(h);
    }
    else
    {
        e = GetLastError();
    }
    return (e);
}

int main(int argc, char *argv[]) 
{
    DWORD pid, ppid;
    int e;
    char fname[MAX_PATH] = {0};
    pid = GetCurrentProcessId();
    ppid = getParentPID(pid);
    e = getProcessName(ppid, fname, MAX_PATH);
    printf("PPID=%d Err=%d EXE={%s}\n", ppid, e, fname);
}

Additional information: OpenProcess is returning 5 (ERROR_ACCESS_DENIED). If I add PROCESS_VM_READ as suggested, it returns 299 (ERROR_PARTIAL_COPY). I can open the current process, but not the parent process.


Solution

  • Call OpenProcess with additional PROCESS_VM_READ flag and it should work:

    h = OpenProcess
        (
        PROCESS_QUERY_INFORMATION | PROCESS_VM_READ,
        FALSE,
        pid
        );
    

    Also look at the possible duplicate mentioned by Mekap