我正在寻找一种使用C#或其他.NET语言查找进程树(如Process Explorer之类的工具所示)的简便方法。查找另一个进程的命令行参数也很有用(System.Diagnostics.Process上的StartInfo似乎对当前进程以外的其他进程无效)。
我认为这些事情只能通过调用win32 api来完成,但是我很高兴被证明是错误的。
如果您不想P / Invoke,则可以使用性能计数器来获取父ID:
foreach (var p in Process.GetProcesses()) { var performanceCounter = new PerformanceCounter("Process", "Creating Process ID", p.ProcessName); var parent = GetProcessIdIfStillRunning((int)performanceCounter.RawValue); Console.WriteLine(" Process {0}(pid {1} was started by Process {2}(Pid {3})", p.ProcessName, p.Id, parent.ProcessName, parent.ProcessId ); } //Below is helper stuff to deal with exceptions from //looking-up no-longer existing parent processes: struct MyProcInfo { public int ProcessId; public string ProcessName; } static MyProcInfo GetProcessIdIfStillRunning(int pid) { try { var p = Process.GetProcessById(pid); return new MyProcInfo() { ProcessId = p.Id, ProcessName = p.ProcessName }; } catch (ArgumentException) { return new MyProcInfo() { ProcessId = -1, ProcessName = "No-longer existant process" }; } }
现在只需将其放入所需的任何树形结构中就可以了。