我具有低于用于通过与NTDLL interop'ing获取子进程的上窗口的列表的代码。是否有一个相当于在Linux上“NtQueryInformationProcess”,这让的我指定的进程(如pbi.InheritedFromUniqueProcessId)的父进程ID?我需要的代码通过单在Linux上运行,所以希望我希望我只需要改变,我得到父进程ID的一部分,所以该代码大多停留在相同的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 的内部:

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'。你还应该加上“使用”围绕一个try / catch,因为我们在打开文件之前,过程中可能会死,等...

其他提示

其实,有一个与冈萨洛的回答一个问题,如果进程名有空格。 此代码对我的作品:

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;
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top