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

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

问题描述

我创建一个使用API​​函数CreateProcess一个子进程。从子过程中,我需要获取父进程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,使用父PI​​D打开父进程,并呼吁 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.

另外,如果你不喜欢的Native 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天全站免登陆