我目前正在将命令行上的 pid 传递给孩子,但有没有办法在 Win32 API 中做到这一点?或者,如果父母已经去世,有人可以减轻我对我传递的 pid 可能在一段时间后属于另一个进程的恐惧吗?
twk
问问题
54503 次
5 回答
55
以防万一其他人遇到此问题并正在寻找代码示例,我最近必须为我正在处理的 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);
}
于 2009-02-17T18:58:42.370 回答
22
更好的方法是调用DuplicateHandle()
创建进程句柄的可继承副本。然后创建子进程并在命令行上传递句柄值。 Close
父进程中的重复句柄。当孩子完成后,它也需要Close
它的副本。
于 2009-06-11T03:07:53.577 回答
21
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;
}
于 2010-06-29T00:27:33.757 回答
13
请注意,如果父进程终止,则 PID 很有可能会被另一个进程重用。这是标准的 Windows 操作。
所以可以肯定的是,一旦你收到父母的 id 并确定它确实是你的父母,你应该打开它的句柄并使用它。
于 2008-10-08T23:10:15.883 回答
3
“或者,如果父母已经去世,有人可以减轻我对我传递的 pid 可能在一段时间后属于另一个进程的恐惧吗?”
是的,PID 可以重复使用。与 UNIX 不同,Windows 不维护强大的父子关系树。
于 2008-10-08T23:09:55.883 回答