Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get parent process in .NET in managed way

I was looking a lot for method to get parent process in .NET, but found only P/Invoke way.

like image 681
abatishchev Avatar asked Dec 27 '08 08:12

abatishchev


People also ask

How do you find the parent process?

Type the simply “pstree” command with the “-p” option in the terminal to check how it displays all running parent processes along with their child processes and respective PIDs. It shows the parent ID along with the child processes IDs.

How do I see the parent process in Windows?

On Windows, the Task Manager does not provide an option to find out the parent process ID. You could use Windows Management Instrumentation Command-line (WMIC) to find out parent process ID.

What is the method used to get a parent process PID?

getppid() method in Python is used to get the parent process ID of the current process.

Do all processes have a parent process?

Every process (except process 0) has one parent process, but can have many child processes. The operating system kernel identifies each process by its process identifier.


2 Answers

Here is a solution. It uses p/invoke, but seems to work well, 32 or 64 cpu:

/// <summary> /// A utility class to determine a process parent. /// </summary> [StructLayout(LayoutKind.Sequential)] public struct ParentProcessUtilities {     // These members must match PROCESS_BASIC_INFORMATION     internal IntPtr Reserved1;     internal IntPtr PebBaseAddress;     internal IntPtr Reserved2_0;     internal IntPtr Reserved2_1;     internal IntPtr UniqueProcessId;     internal IntPtr InheritedFromUniqueProcessId;      [DllImport("ntdll.dll")]     private static extern int NtQueryInformationProcess(IntPtr processHandle, int processInformationClass, ref ParentProcessUtilities processInformation, int processInformationLength, out int returnLength);      /// <summary>     /// Gets the parent process of the current process.     /// </summary>     /// <returns>An instance of the Process class.</returns>     public static Process GetParentProcess()     {         return GetParentProcess(Process.GetCurrentProcess().Handle);     }      /// <summary>     /// Gets the parent process of specified process.     /// </summary>     /// <param name="id">The process id.</param>     /// <returns>An instance of the Process class.</returns>     public static Process GetParentProcess(int id)     {         Process process = Process.GetProcessById(id);         return GetParentProcess(process.Handle);     }      /// <summary>     /// Gets the parent process of a specified process.     /// </summary>     /// <param name="handle">The process handle.</param>     /// <returns>An instance of the Process class.</returns>     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)         {             // not found             return null;         }     } } 
like image 114
Simon Mourier Avatar answered Sep 29 '22 04:09

Simon Mourier


This code provides a nice interface for finding the Parent process object and takes into account the possibility of multiple processes with the same name:

Usage:

Console.WriteLine("ParentPid: " + Process.GetProcessById(6972).Parent().Id); 

Code:

public static class ProcessExtensions {     private static string FindIndexedProcessName(int pid) {         var processName = Process.GetProcessById(pid).ProcessName;         var processesByName = Process.GetProcessesByName(processName);         string processIndexdName = null;          for (var index = 0; index < processesByName.Length; index++) {             processIndexdName = index == 0 ? processName : processName + "#" + index;             var processId = new PerformanceCounter("Process", "ID Process", processIndexdName);             if ((int) processId.NextValue() == pid) {                 return processIndexdName;             }         }          return processIndexdName;     }      private static Process FindPidFromIndexedProcessName(string indexedProcessName) {         var parentId = new PerformanceCounter("Process", "Creating Process ID", indexedProcessName);         return Process.GetProcessById((int) parentId.NextValue());     }      public static Process Parent(this Process process) {         return FindPidFromIndexedProcessName(FindIndexedProcessName(process.Id));     } } 
like image 42
Michael Hale Avatar answered Sep 29 '22 04:09

Michael Hale