要可靠地检查一个Windows进程是否是C++中另一个进程的父进程,可以使用Windows API函数NtQueryInformationProcess
。以下是一个示例代码:
#include<iostream>
#include<Windows.h>
#include <TlHelp32.h>
#include <winternl.h>
typedef LONG(NTAPI *_NtQueryInformationProcess)(
HANDLE ProcessHandle,
PROCESSINFOCLASS ProcessInformationClass,
PVOID ProcessInformation,
ULONG ProcessInformationLength,
PULONG ReturnLength);
bool IsParentProcess(DWORD parentId, DWORD childId)
{
_NtQueryInformationProcess NtQueryInformationProcess = (_NtQueryInformationProcess)GetProcAddress(GetModuleHandleA("ntdll"), "NtQueryInformationProcess");
HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, childId);
if (hProcess == NULL)
return false;
ULONG cbBuffer = sizeof(PROCESS_BASIC_INFORMATION);
PROCESS_BASIC_INFORMATION pbi = {0};
NTSTATUS status = NtQueryInformationProcess(hProcess, ProcessBasicInformation, &pbi, cbBuffer, NULL);
if (status != 0)
return false;
return pbi.InheritedFromUniqueProcessId == parentId;
}
int main()
{
DWORD parentProcessId = 1234; // 替换为要检查的父进程ID
DWORD childProcessId = 5678; // 替换为要检查的子进进程ID
if (IsParentProcess(parentProcessId, childProcessId))
std::cout << "子进程是父进程的子进程"<< std::endl;
else
std::cout << "子进程不是父进程的子进程"<< std::endl;
return 0;
}
这个代码示例使用了NtQueryInformationProcess
函数来获取进程的基本信息,并检查InheritedFromUniqueProcessId
字段是否与给定的父进程ID匹配。如果匹配,则说明子进程是父进程的子进程。
请注意,这个代码示例仅适用于Windows操作系统,并且需要管理员权限才能运行。
领取专属 10元无门槛券
手把手带您无忧上云