在.NET中查找进程树 [英] find the process tree in .NET

查看:73
本文介绍了在.NET中查找进程树的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种简单的方法,以C#或其他.NET语言查找过程树(如Process Explorer之类的工具所示)。查找另一个进程的命令行参数也很有用(System.Diagnostics.Process上的StartInfo似乎对当前进程以外的其他进程无效)。

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.

这篇关于在.NET中查找进程树的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆