It is common that you may want to find the process tree, where given the name of the process, you would like to find out its children and children of the children.
However, natively, you will not be able to tell who is the parent of the given process. by the System.Diagnostic.Process won't have a property to tell who is the parent of the current process. See the process class here.
In this example, we will see an example that uses the SystemManagement classes to help find the relationship between processes.
public static class MyExtensions
{
public static int GetParentProcessId(this Process p)
{
int parentId = 0;
try
{
ManagementObject mo = new ManagementObject("win32_process.handle='" + p.Id + "'");
mo.Get(); // why do we call the ManagementObject.Get() method
if (mo != null)
{
parentId = Convert.ToInt32(mo["ParentProcessId"]);
}
}
catch (Exception ex_)
{
Console.WriteLine(ex_.ToString());
parentId = 0;
}
return parentId;
}
}
and then , with that wen can tell who is the parent of a particular process by check the value returned by the GetParentProcessID and compare it with the target process's id. Here is the code that find the children and children of children plus the process itself.
class Program
{
private static void GetProcessAndChildren(Process[] plist, Process parent, List<Process> output, int indent)
{
Debug.Assert(plist != null && parent != null);
foreach (var p in plist)
{
if (p.GetParentProcessId() == parent.Id)
{
GetProcessAndChildren(plist, p, output, indent + 1); // find further child
}
}
output.Add(parent); // do not forget the parent?
Console.WriteLine(String.Format("{0," + indent * 4 + "} {1}", parent.Id, parent.MainModule.ModuleName));
}
static void Main(string[] args)
{
if (args.Length < 1)
{
Console.WriteLine("Usage : ProcessTree <pid>");
return;
}
int pid = int.Parse(args[0]);
Process root = Process.GetProcessById(pid);
if (root != null)
{
var list = new List<Process>();
GetProcessAndChildren(Process.GetProcesses(), root, list, 1);
foreach (var p in list)
{
try
{
//p.Kill();
// do something on the process found
}
catch (Exception ex_)
{
Console.WriteLine(ex_.ToString());
}
}
}
else
{
Console.WriteLine("Unknown process id:{0}", pid);
}
}
}
You can run this by input some process id from the task bar..