windows 如何在 C# 中获取给定服务的子进程列表?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1073615/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 12:44:59  来源:igfitidea点击:

How can I get a list of child processes for a given service in C#?

c#windowsprocessservice

提问by Bardsley

I have a service which creates a number of child processes. Using c# I need to determine the number of these child processes which are currently running.

我有一个创建多个子进程的服务。使用 c# 我需要确定当前正在运行的这些子进程的数量。

For example I have a service running called "TheService". This spawns 5 child processes, all called "process.exe". Is it possible to determine the number of child processes running under the service? Essentially I need to know the number of instances of "process.exe" given only the name of the service/service process name.

例如,我有一个名为“TheService”的服务正在运行。这会产生 5 个子进程,都称为“process.exe”。是否可以确定在该服务下运行的子进程数?本质上,我只需要知道服务/服务进程名称的名称,就需要知道“process.exe”的实例数。

回答by Richard

You need to use WMI, the Win32_Processclass includes the parent process id. So a WQL query (see System.Management namespace for WMI under .NET) like:

您需要使用 WMI,Win32_Process类包含父进程 ID。因此,WQL 查询(请参阅 .NET 下 WMI 的 System.Management 命名空间)如下所示:

SELECT * FROM Win32_Process Where ParentProcessId = n

replacing nwith the service's process id.

n替换为服务的进程 ID。

EDIT Sample code (based on code by Arsen Zahray):

编辑示例代码(基于Arsen Zahray 的代码):

static List<Process> GetChildProcesses(int parentId) {
  var query = "Select * From Win32_Process Where ParentProcessId = "
          + parentId;
  ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
  ManagementObjectCollection processList = searcher.Get();

  var result = processList.Cast<ManagementObject>().Select(p =>
    Process.GetProcessById(Convert.ToInt32(p.GetPropertyValue("ProcessId")));
  ).ToList();

  return result;
}

回答by J?rn Schou-Rode

I am not sure exactly what you mean by "the name of the service" - would that be process.exe?

我不确定您所说的“服务名称”究竟是什么意思 - 那是 process.exe 吗?

If so, the static method Process.GetProcessesByName()should do the trick:

如果是这样,静态方法Process.GetProcessesByName()应该可以解决问题:

Process[] procs = Process.GetProcessesByName("process");
Console.WriteLine(procs.Length);

Let me know if I misunderstood your question.

如果我误解了您的问题,请告诉我。