2

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?

E.T.
  • 949
  • 8
  • 21

2 Answers2

1

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

holtavolt
  • 4,378
  • 1
  • 26
  • 40
1

.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:

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.

ivan_pozdeev
  • 33,874
  • 19
  • 107
  • 152