从子进程获取父进程 ID [英] Fetching parent process Id from child process

查看:31
本文介绍了从子进程获取父进程 ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I create a child process using CreateProcess API. From the child process I need to fetch the parent's process id.

如果我的进程树有一个子进程和一个孙子进程.我还需要从孙子进程中获取最顶端的父进程 ID.

If my process tree have a child and a grand child. I need to fetch the top most parent's process id from the grand child as well.

推荐答案

您应该使用 Native API 和 GetProcAddress 来查找 NtQueryInformationProcess 的地址.

You should use the Native API and GetProcAddress to find the address of 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

要获取祖父 PID,请使用父 PID 打开父进程并在父进程上再次调用 NtQueryInformationProcess.

To get the grandparent PID, open the parent process using the parent PID and call NtQueryInformationProcess again on the parent process.

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

Note * - Strictly speaking, the parent process (the process which created the child process) is not actually recorded. InheritedFromUniqueProcessId just gives you the process from which attributes were inherited. But this is very rarely a problem.

或者,如果您不喜欢本机 API,请使用 CreateToolhelp32Snapshot 带有 TH32CS_SNAPPROCESS,它为您提供所需的信息,但您必须在列表中进行搜索.

Alternatively, if you don't like the Native API, use CreateToolhelp32Snapshot with TH32CS_SNAPPROCESS, which gives you the required information, except that you'll have to search through the list.

这篇关于从子进程获取父进程 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆