How can I reliably check if one Windows process is the parent of another in C ++?

I am working on a function that returns me the PID of the parent process for a given PID. The prototype of the function is

DWORD getParentPid( DWORD pid ); 

To do this, I use the CreateToolhelp32Snapshot function (and related functions) to get the PROCESSENTRY32 for my PID pid . Then I can use the th32ParentProcessId field of the structure to get the PID of the process that created my given process.

However, since the parent process may already have been destroyed (and the PID could be reused by Windows), I use the GetProcessTimes function to get the creation time of the intended parent and child process, and then compare them using CompareFileTime .

If CompareFileTime returns -1 , I know that a process with a parent id was created before my child process, so it really is a parent. Otherwise, this is apparently a reusable identifier, and the parent PID is invalid (it no longer refers to the original parent).

The problem is that it very much depends on a strictly monotonous system clock and the granularity of GetProcessTimes . I really experienced cases where CompareFileTime returned 0 (which means "equal time"), even if the process in question is indeed in a parent-child relationship. I could change my check so that the value of the result CompareFileTime <= 0 was considered to indicate to the parent, but then I would break the (theoretical) case where the parent created the child process, then the parent was destroyed, and then Windows reused the PID - all within 100ns (which is the permission of GetProcessTimes ).

I wonder if there is another, more reliable mechanism for checking that some process is really the parent of another process in C ++?

Edit: I need this function to define all child processes (this means enabling grand-child processes). CreateToolhelp32Snapshot allows me to CreateToolhelp32Snapshot over all the processes, but I need to look at the parent PID of each of them to find out if this is a child of my process.

+7
source share
2 answers

Sample here:

http://msdn.microsoft.com/en-us/library/ms686701(v=vs.85).aspx

Shows a CreateToolhelp32Snapshot call with parameter 0 for processId and uses the parameter TH32CS_SNAPPROCESS, which says that it captures all processes. Then, as soon as you get a snapshot, as in the example, you can walk through the processes as they existed in the snapshot. The parent ID must be valid within the snapshot, because you look at the state of all processes as they existed at the time the snapshot was taken. You do not need to worry about how you compare the start time of the process.

0
source

If the process was created while your application was running, you can simply iterate over it over time and intercept the reuse of PID.

+1
source

All Articles