进程树进程

2023-09-02 02:01:08 作者:东篱

我正在寻找一个简单的方法来查找进程树(如图样的Process Explorer工具),在C#或其他.NET语言。这也将是有益的找到另一个进程的命令行参数(在的StartInfo上的System.Diagnostics.Process似乎是工艺比当前进程的其他无效)。

I'm looking for an easy way to find the process tree (as shown by tools like Process Explorer), in C# or other .Net language. It would also be useful to find the command-line arguments of another process (the StartInfo on System.Diagnostics.Process seems invalid for process other than the current process).

我觉得这些事情只能通过调用Win32 API的工作要做,但我很乐意被证明是错误的。

I think these things can only be done by invoking the win32 api, but I'd be happy to be proved wrong.

谢谢!

罗伯特·

推荐答案

如果你不希望的P / Invoke,你可以抓住父ID的使用性能计数器:

If you don't want to P/Invoke, you can grab the parent Id's with a performance counter:

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" };
    }
}

现在只是把它变成什么树结构要和你做。

now just put it into whatever tree structure want and you are done.