Home >Backend Development >C++ >How to Get the Parent Process in .NET Without Using P/Invoke?

How to Get the Parent Process in .NET Without Using P/Invoke?

Linda Hamilton
Linda HamiltonOriginal
2025-01-28 05:12:10438browse

How to Get the Parent Process in .NET Without Using P/Invoke?

<.> Get the parent process in the .NET, no P/Invoke

Getting the parent process in .NET is a common task that can be implemented using platform calls (P/Invoke). However, this article introduces an alternative that does not need to use P/Invoke.

This solution uses the NTQUERYINFORMATIONPROCESS function in the ntdll.dll library, but it does not interact directly through P/Invoke, but uses the ParentProcessutilities class to abstract the process.

ParentProcessUtilities classes contain static methods, such as GetpaRENTPROCESS, which accepts an instance of the procestess class that indicates the processes of the parent process.
<code class="language-csharp">[StructLayout(LayoutKind.Sequential)]
public struct ParentProcessUtilities
{
    // 这些成员必须与PROCESS_BASIC_INFORMATION匹配
    internal IntPtr Reserved1;
    internal IntPtr PebBaseAddress;
    internal IntPtr Reserved2_0;
    internal IntPtr Reserved2_1;
    internal IntPtr UniqueProcessId;
    internal IntPtr InheritedFromUniqueProcessId;
}</code>

NtQueryInformationProcess function to retrieve the basic information of the specified process, including the inheritance process ID. By querying this information and converting it into a process instance, this solution allows to easily retrieve the parent process in the hosting code without using P/Invoke.
<code class="language-csharp">public static Process GetParentProcess(IntPtr handle)
{
    ParentProcessUtilities pbi = new ParentProcessUtilities();
    int returnLength;
    int status = NtQueryInformationProcess(handle, 0, ref pbi, Marshal.SizeOf(pbi), out returnLength);
    if (status != 0)
        throw new Win32Exception(status);

    try
    {
        return Process.GetProcessById(pbi.InheritedFromUniqueProcessId.ToInt32());
    }
    catch (ArgumentException)
    {
        // 未找到
        return null;
    }
}</code>

The above is the detailed content of How to Get the Parent Process in .NET Without Using P/Invoke?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn