Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can a Win32 process get the pid of its parent?

Tags:

process

winapi

I'm currently passing the pid on the command line to the child, but is there a way to do this in the Win32 API? Alternatively, can someone alleviate my fear that the pid I'm passing might belong to another process after some time if the parent has died?

like image 803
twk Avatar asked Oct 08 '08 22:10

twk


People also ask

How do you find the parent PID of a process?

Type the simply “pstree” command with the “-p” option in the terminal to check how it displays all running parent processes along with their child processes and respective PIDs. It shows the parent ID along with the child processes IDs.

Where is parent process PID in Windows?

On Windows, the Task Manager does not provide an option to find out the parent process ID. You could use Windows Management Instrumentation Command-line (WMIC) to find out parent process ID.

How do I get PID and PPID?

How to get a parent PID (PPID) from a child's process ID (PID) using the command-line. e.g. ps -o ppid= 2072 returns 2061 , which you can easily use in a script etc. ps -o ppid= -C foo gives the PPID of process with command foo . You can also use the old fashioned ps | grep : ps -eo ppid,comm | grep '[f]oo' .

What can be the PID of a child process?

The child process has a unique process ID (PID) that does not match any active process group ID. The child has a different parent process ID, that is, the process ID of the process that called fork(). The child has its own copy of the parent's file descriptors.


2 Answers

Just in case anyone else runs across this question and is looking for a code sample, I had to do this recently for a Python library project I'm working on. Here's the test/sample code I came up with:

#include <stdio.h> #include <windows.h> #include <tlhelp32.h>  int main(int argc, char *argv[])  {     int pid = -1;     HANDLE h = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);     PROCESSENTRY32 pe = { 0 };     pe.dwSize = sizeof(PROCESSENTRY32);      //assume first arg is the PID to get the PPID for, or use own PID     if (argc > 1) {         pid = atoi(argv[1]);     } else {         pid = GetCurrentProcessId();     }      if( Process32First(h, &pe)) {         do {             if (pe.th32ProcessID == pid) {                 printf("PID: %i; PPID: %i\n", pid, pe.th32ParentProcessID);             }         } while( Process32Next(h, &pe));     }      CloseHandle(h); } 
like image 80
Jay Avatar answered Sep 17 '22 07:09

Jay


A better way to do this is to call DuplicateHandle() to create an inheritable duplicate of your process handle. Then create the child process and pass the handle value on the command line. Close the duplicated handle in the parent process. When the child's done, it will need to Close its copy as well.

like image 25
Peter Ruderman Avatar answered Sep 20 '22 07:09

Peter Ruderman