I am working on a MS Windows C# Winform project and I cannot get the PPID (Parent Process ID). I've found many solutions but none that seem to work with said OS and language.
How can I get PPID?
If you can use System.Management, it's easy enough:
private static int GetParentProcess(int Id)
{
int parentPid = 0;
using (ManagementObject mo = new ManagementObject("win32_process.handle='" + Id.ToString() + "'"))
{
mo.Get();
parentPid = Convert.ToInt32(mo["ParentProcessId"]);
}
return parentPid;
}
Otherwise you may have to resort to P/Invoke calls via CreateToolhelp32Snapshot like this
.NET doesn't provide a built-in way. Process.GetProcesses()
itself uses NtQuerySystemInformation(SystemProcessInformation,)
to query most process properties, its returned entries have a PPID field that the code doesn't use.
So, the way to go is to use an external technique:
WMI as per holtavolt's answer
toolhelp32
API as per e.g. Getting The ID of a process from Process name . It can snapshot either a specific or all processes.
NtQueryInformationProcess(,ProcessBasicInformation,)
as per Fetching parent process Id from child process .
The aforementioned NtQuerySystemInformation(SystemProcessInformation,)
Other things to note:
Keep in mind that any of the processes you got info on can end at any moment (the exception is critical system processes but you probably won't be much interested in them)
PIDs are reused in Windows without resetting PPIDs. To filter out possible "fake parents", look at StartTime
. The real parent would have started earlier than the child, a fake one - later.