Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I'm working on a function which gets me the PID of the parent process for a given PID. The prototype of the function is

DWORD getParentPid( DWORD pid );

To do so, I'm using the CreateToolhelp32Snapshot function (and related functions) to get the PROCESSENTRY32 structure for my given PID pid. I can then use the th32ParentProcessId field of the structure to get the PID of the process which created my given process.

However, since the parent process might have been destroyed already (and it's PID might have been reused by Windows), I'm using the GetProcessTimes function to get the creation times of the supposed parent and the child process and then compare those using CompareFileTime.

If CompareFileTime returns -1, I know that the process with the parent ID was created before my child process, so it's indeed the parent. Otherwise, it's apparently a re-used ID - and the parent PID is invalid (it doesn't reference the original parent anymore).

The issue with this is that it very much relies on a strictly monotonous system clock and the granularity of GetProcessTimes. I did experience cases in which CompareFileTime returned 0 (which means "equal time") even though the process being considered were indeed in a parent-child relationship. I could change my check so that a CompareFileTime result value <= 0 would be considered to indicate a parent, but then I would break the (theoretical) case where a parent created a child process, then the parent was destroyed, and then Windows re-used the PID - all within 100ns (which is the resolution of GetProcessTimes).

I wonder - is there a different, more reliably, mechanism to verify that some process is indeed the parent of another process in C++?

Edit: I need this function in order to determine all child processes (this means including grand-child processes). The CreateToolhelp32Snapshot lets me iterate over all processes but I need to look at the parent PID of each of them to tell whether it's a child of my process at hand.

like image 895
Frerich Raabe Avatar asked Jul 06 '11 07:07

Frerich Raabe


1 Answers

If the process(es) have been created whilst your app is running, you could just iterate over it repeatedly over time and catch PID re-use.

like image 181
Puppy Avatar answered Oct 19 '22 23:10

Puppy