我正在将命令行上的pid传递给子进程,但有没有办法在Win32 API中执行此操作?或者,有人可以减轻我的担心,如果父母已经去世,我经过的pid可能会在一段时间后属于另一个过程吗?
Jay*_*Jay 50
为了防止其他人遇到这个问题并且正在寻找代码示例,我最近必须为我正在研究的Python库项目执行此操作.这是我提出的测试/示例代码:
#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);
}
Run Code Online (Sandbox Code Playgroud)
Pet*_*man 20
更好的方法是调用DuplicateHandle()创建进程句柄的可继承副本.然后创建子进程并在命令行上传递句柄值. Close父进程中的重复句柄.当孩子完成后,它也需要Close复制.
小智 20
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;
}
Run Code Online (Sandbox Code Playgroud)
sho*_*osh 10
请注意,如果父进程终止,则很可能甚至可能将PID重用于另一个进程.这是标准的Windows操作.
所以可以肯定的是,一旦你收到父母的id,并确定它真的是你的父母,你应该打开它的句柄并使用它.