C#/mono:获取Windows和Linux上的子进程列表 [英] C#/mono: get list of child processes on Windows and Linux
问题描述
我有下面的代码,用于通过与ntdll互操作来获取Windows上的子进程列表.在Linux上是否有等效于'NtQueryInformationProcess'的信息,它使我知道指定进程的父进程的进程ID(例如pbi.InheritedFromUniqueProcessId)?我需要代码通过Mono在Linux上运行,因此希望我只需要更改获取父进程ID的部分,以便代码与Windows上的代码基本相同.
I have the code below for getting a list of child processes on windows by interop'ing with ntdll. Is there an equivalent to 'NtQueryInformationProcess' on Linux, which get's me the process id of the parent of a specified process (like pbi.InheritedFromUniqueProcessId)? I need the code to run on Linux through Mono so hopefully I am hoping I need to change only the part where I get the parent process ID so the code stays mostly the same as on Windows.
public IList< Process > GetChildren( Process parent )
{
List< Process > children = new List< Process >();
Process[] processes = Process.GetProcesses();
foreach (Process p in processes)
{
ProcessBasicInformation pbi = new ProcessBasicInformation();
try
{
uint bytesWritten;
NtQueryInformationProcess(p.Handle,
0, ref pbi, (uint)Marshal.SizeOf(pbi),
out bytesWritten); // == 0 is OK
if (pbi.InheritedFromUniqueProcessId == parent.Id)
children.AddRange(GetChildren(p));
}
catch
{
}
}
return children;
}
推荐答案
在Linux中查找给定进程的所有子级的一种方法是在 foreach 中执行以下操作:
One way of finding all the children of a given process in Linux is to do something like this inside your foreach:
string line;
using (StreamReader reader = new StreamReader ("/proc/" + p.Id + "/stat")) {
line = reader.ReadLine ();
}
string [] parts = line.Split (new char [] {' '}, 5); // Only interested in field at position 3
if (parts.Legth >= 4) {
int ppid = Int32.Parse (parts [3]);
if (ppid == parent.Id) {
// Found a children
}
}
有关/proc/[id]/stat包含的内容的更多信息,请参见"proc"的手册页.您还应该在'using'周围添加try/catch,因为在打开文件等之前,该过程可能会终止.
For more information on what /proc/[id]/stat contains, see the manual page for 'proc'. You should also add a try/catch around the 'using' because the process might die before we open the file, etc...
这篇关于C#/mono:获取Windows和Linux上的子进程列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!