C#/ mono:获取Windows和Linux上的子进程列表

我有以下代码通过与ntdll交互获取Windows上的子进程列表。 在Linux上有没有相当于’NtQueryInformationProcess’的东西,它是我指定进程的父进程的进程ID(如pbi.InheritedFromUniqueProcessId)? 我需要通过Mono在Linux上运行代码,所以我希望我只需要更改获得父进程ID的部分,以便代码与Windows上的代码保持一致。

public IList GetChildren( Process parent ) { List children = new List(); 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中执行以下操作

 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,因为在打开文件之前进程可能会死掉,等等……

实际上,如果进程名称中包含空格,那么Gonzalo的答案就会出现问题。 这段代码适合我:

 public static int GetParentProcessId(int processId) { string line; using (StreamReader reader = new StreamReader ("/proc/" + processId + "/stat")) line = reader.ReadLine (); int endOfName = line.LastIndexOf(')'); string [] parts = line.Substring(endOfName).Split (new char [] {' '}, 4); if (parts.Length >= 3) { int ppid = Int32.Parse (parts [2]); return ppid; } return -1; }