从子进程获取父进程Id

Mut*_*pan 2 c windows winapi process

我使用CreateProcess API创建子进程.从子进程我需要获取父进程的id.

如果我的进程树有一个孩子和一个大孩子.我还需要从大孩子那里获取最顶级父母的进程ID.

wj3*_*j32 6

您应该使用Native API并GetProcAddress查找地址NtQueryInformationProcess.

typedef struct _PROCESS_BASIC_INFORMATION
{
    NTSTATUS ExitStatus;
    PPEB PebBaseAddress;
    ULONG_PTR AffinityMask;
    KPRIORITY BasePriority;
    HANDLE UniqueProcessId;
    HANDLE InheritedFromUniqueProcessId;
} PROCESS_BASIC_INFORMATION, *PPROCESS_BASIC_INFORMATION;

NTSYSCALLAPI
NTSTATUS
NTAPI
NtQueryInformationProcess(
    __in HANDLE ProcessHandle,
    __in PROCESS_INFORMATION_CLASS ProcessInformationClass,
    __out_bcount(ProcessInformationLength) PVOID ProcessInformation,
    __in ULONG ProcessInformationLength,
    __out_opt PULONG ReturnLength
    );

PROCESS_BASIC_INFORMATION basicInfo;

NtQueryInformationProcess(NtCurrentProcess(), ProcessBasicInformation, &basicInfo, sizeof(basicInfo), NULL);
// My parent PID (*) is in basicInfo.InheritedFromUniqueProcessId
Run Code Online (Sandbox Code Playgroud)

要获取祖父PID,请使用父PI​​D打开父进程,然后NtQueryInformationProcess再次在父进程上调用.

注意* - 严格地说,父进程(创建子进程的进程)实际上没有记录.InheritedFromUniqueProcessId只是为您提供继承属性的过程.但这很少是一个问题.

或者,如果您不喜欢Native API,请使用CreateToolhelp32Snapshot with TH32CS_SNAPPROCESS,它会为您提供所需的信息,但您必须搜索列表.

  • NtQueryInformationProcess 现在被标记为过时。 (2认同)