Skip to content

Instantly share code, notes, and snippets.

@skahwah
Created January 27, 2021 21:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save skahwah/9378581ff33dbd7dd118c5727cbd0833 to your computer and use it in GitHub Desktop.
Save skahwah/9378581ff33dbd7dd118c5727cbd0833 to your computer and use it in GitHub Desktop.
//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