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.
Frerich raabe
source share