Windows – Fetching parent process Id from child process

c++processwinapiwindows

I create a child process using CreateProcess API. From the child process I need to fetch the parent's process id.

If my process tree have a child and a grand child. I need to fetch the top most parent's process id from the grand child as well.

Best Solution

You should use the Native API and GetProcAddress to find the address of NtQueryInformationProcess.

typedef struct _PROCESS_BASIC_INFORMATION
{
    NTSTATUS ExitStatus;
    PPEB PebBaseAddress;
    ULONG_PTR AffinityMask;
    KPRIORITY BasePriority;
    HANDLE UniqueProcessId;
    HANDLE InheritedFromUniqueProcessId;
} PROCESS_BASIC_INFORMATION, *PPROCESS_BASIC_INFORMATION;

NTSYSCALLAPI
NTSTATUS
NTAPI
NtQueryInformationProcess(
    __in HANDLE ProcessHandle,
    __in PROCESS_INFORMATION_CLASS ProcessInformationClass,
    __out_bcount(ProcessInformationLength) PVOID ProcessInformation,
    __in ULONG ProcessInformationLength,
    __out_opt PULONG ReturnLength
    );

PROCESS_BASIC_INFORMATION basicInfo;

NtQueryInformationProcess(NtCurrentProcess(), ProcessBasicInformation, &basicInfo, sizeof(basicInfo), NULL);
// My parent PID (*) is in basicInfo.InheritedFromUniqueProcessId

To get the grandparent PID, open the parent process using the parent PID and call NtQueryInformationProcess again on the parent process.

Note * - Strictly speaking, the parent process (the process which created the child process) is not actually recorded. InheritedFromUniqueProcessId just gives you the process from which attributes were inherited. But this is very rarely a problem.

Alternatively, if you don't like the Native API, use CreateToolhelp32Snapshot with TH32CS_SNAPPROCESS, which gives you the required information, except that you'll have to search through the list.