Win32进程如何获得其父进程的PID?

我目前正在将命令行上的PID传递给孩子,但有没有办法在Win32 API中做到这一点? 或者,如果父母已经死亡,那么有人可以减轻我的恐惧,即我经过的PID可能会在一段时间后属于另一个过程?

请注意,如果父进程终止,则很可能甚至有可能将PID重用于另一个进程。 这是标准的Windows操作。

所以可以肯定的是,一旦你收到父母的身份证,并确定它确实是你的父母,你应该打开一个句柄,并使用它。

为了防止其他人遇到这个问题,并且正在寻找一个代码示例,我最近必须为我正在开发的Python库项目做这个工作。 这里是我提出的testing/示例代码:

#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); } 
 ULONG_PTR GetParentProcessId() // By Napalm @ NetCore2K { ULONG_PTR pbi[6]; ULONG ulSize = 0; LONG (WINAPI *NtQueryInformationProcess)(HANDLE ProcessHandle, ULONG ProcessInformationClass, PVOID ProcessInformation, ULONG ProcessInformationLength, PULONG ReturnLength); *(FARPROC *)&NtQueryInformationProcess = GetProcAddress(LoadLibraryA("NTDLL.DLL"), "NtQueryInformationProcess"); if(NtQueryInformationProcess){ if(NtQueryInformationProcess(GetCurrentProcess(), 0, &pbi, sizeof(pbi), &ulSize) >= 0 && ulSize == sizeof(pbi)) return pbi[5]; } return (ULONG_PTR)-1; } 

更好的方法是调用DuplicateHandle()来创build一个可inheritance的进程句柄副本。 然后创buildsubprocess并在命令行上传递句柄值。 Close父进程中的重复句柄。 当孩子完成时,还需要Close其副本。

“或者,如果父母已经死亡,那么有人可以减轻我担心我经过的pid可能会在一段时间后属于另一个过程吗?

是的,PID可以重复使用。 与UNIX不同,Windows不维护强大的父子关系树。