通过查询进程的 PBI信息(进程基础信息)来获取该进程的父进程ID
补充:
PEB(进程环境信息)
// https://learn.microsoft.com/en-us/windows/win32/api/winternl/nf-winternl-ntqueryinformationprocess
typedef struct KERNEL_PROCESS_BASIC_INFORMATION
{
NTSTATUS ExitStatus;
PPEB PebBaseAddress;
ULONG_PTR AffinityMask;
KPRIORITY BasePriority;
ULONG_PTR UniqueProcessId;
ULONG_PTR InheritedFromUniqueProcessId;
} KERNEL_PROCESS_BASIC_INFORMATION, * KERNEL_PPROCESS_BASIC_INFORMATION;
int Win32Native::GetInheritedFromUniqueProcessId(int process_id) noexcept
{
typedef NTSTATUS(WINAPI* NtQueryInformationProcess_Proc)(HANDLE, UINT, PVOID, ULONG, PULONG);
DWORD dwInheritedFromUniqueProcessId = 0;
HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, process_id);
if (NULL != hProcess)
{
KERNEL_PROCESS_BASIC_INFORMATION pbi;
ZeroMemory(&pbi, sizeof(pbi));
static NtQueryInformationProcess_Proc NtQueryInformationProcess = (NtQueryInformationProcess_Proc)GetProcAddress("ntdll.dll", "NtQueryInformationProcess");
if (NULL != NtQueryInformationProcess)
{
NTSTATUS status = NtQueryInformationProcess(hProcess, 0, &pbi, sizeof(pbi), NULL);
if (status == 0)
{
dwInheritedFromUniqueProcessId = (DWORD)pbi.InheritedFromUniqueProcessId;
}
}
CloseHandle(hProcess);
}
return dwInheritedFromUniqueProcessId;
}