Method for WIN32 programs to get the ID of the parent process

  • 2020-04-02 02:34:16
  • OfStack

Anyone who has studied Windows programming knows that processes in Windows can have parent-child relationships, and processes that have parent-child relationships will exit once the parent process ends. But if there is no parent-child relationship between processes, how do we make the child process exit at the same time as the parent process exits? There are many methods, this article introduces one of the use of the parent process ID scheme, the principle is simple: first get the parent process ID, then get the parent process Handle by ID, by monitoring the parent process Handle to determine whether the child process exit. So, the key here is how to get the ID of the parent process.

To get the parent ID, you need to use an API that Microsoft has not disclosed:


NTSTATUS WINAPI NtQueryInformationProcess(
 __in    HANDLE ProcessHandle,
 __in    PROCESSINFOCLASS ProcessInformationClass,
 __out   PVOID ProcessInformation,
 __in    ULONG ProcessInformationLength,
 __out_opt PULONG ReturnLength
);

This API is located in ntdll.dll and gets the relevant type definition by referring to the header file winternl.h. Once we have this function, the next step is to understand the meaning of each function parameter. Here we focus on the second parameter, PROCESSINFOCLASS structure:


 typedef struct _PROCESS_BASIC_INFORMATION {
  PVOID Reserved1;
  PPEB PebBaseAddress;
  PVOID Reserved2[2];
  ULONG_PTR UniqueProcessId;
  PVOID Reserved3;
} PROCESS_BASIC_INFORMATION;

This is the structure definition given in MSDN. So far, we still don't know where the Parent process gets its ID from. Just as the saying goes, there is no airtight wall in the world. After the crack of numerous masters, in fact, the last field Reserved3 is the ID of Parent process, as long as we convert it to a DWORD value.

After testing on x86 and x64 windows2003 and windows20008 platforms, it is indeed the ID of the Parent process.

Now that you know where the Parent process ID comes from, it's easy to follow the basic steps:

1. Get your own process ID, GetCurrentProcessID()

2. Get the process query handle and call OpenProcess() with the PROCESS_QUERY_INFORMATION flag

3. Call NtQueryInformationProcess () to query the process information

4. Get the parent process handle, or call OpenProcess()

5. Start a thread to wait for the parent process to exit, WaitForSingleObject(ParentHandle, INFINITE)

This is done so that the child process can exit whether the parent process exits normally or terminates abnormally.


Related articles: