Created
January 27, 2021 21:06
-
-
Save skahwah/9378581ff33dbd7dd118c5727cbd0833 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//c:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe get-pid-and-ppid.cs | |
using System; | |
using System.ComponentModel; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
using System.Runtime.InteropServices; | |
using Microsoft.Win32.SafeHandles; | |
using System.IO; | |
using System.Diagnostics; | |
class Program | |
{ | |
static void Main() | |
{ | |
Process[] procs = Process.GetProcesses(); | |
foreach (Process proc in procs) | |
{ | |
try | |
{ | |
Console.WriteLine("Name: " + proc.ProcessName + "PID: " + proc.Id + " Parent: " + ParentProcessUtilities.GetParentProcess(proc.Id).ProcessName + " PPID: " + ParentProcessUtilities.GetParentProcess(proc.Id).Id); | |
} | |
catch | |
{ | |
continue; | |
} | |
} | |
} | |
[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); | |
public static Process GetParentProcess() | |
{ | |
return GetParentProcess(Process.GetCurrentProcess().Handle); | |
} | |
public static Process GetParentProcess(int id) | |
{ | |
Process process = Process.GetProcessById(id); | |
return GetParentProcess(process.Handle); | |
} | |
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; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment