Monitor child processes of a process

前端 未结 3 2074
遥遥无期
遥遥无期 2020-12-11 00:35

I\'m running .exe file using this code:

Process proc = Process.Start(\"c:\\program.exe\");
proc.WaitForExit();

If I start Stopwatch

相关标签:
3条回答
  • 2020-12-11 00:58

    you can't wait for process(B) another process(A) is running, if that process(A) isn't waiting for the process(B). what you can do is track the process using Process.GetProcessesByName() if you know it's name

    0 讨论(0)
  • 2020-12-11 01:08

    Take a look at this - Find all child processes of my own .NET process / find out if a given process is a child of my own? or http://social.msdn.microsoft.com/Forums/vstudio/en-US/d60f0793-cc92-48fb-b867-dd113dabcd5c/how-to-find-the-child-processes-associated-with-a-pid. They provide ways to find child processes by a parent PID (which you have).

    You can write monitor the process you create and also get its children. You could then track everything, and wait for them all to finish. I say "try" because I'm not sure you could catch very rapid changes (a process starting others and then dying before you get his children).

    0 讨论(0)
  • 2020-12-11 01:11

    Here is the solution that the asker found:

    public static class ProcessExtensions
    {
        public static IEnumerable<Process> GetChildProcesses(this Process process)
        {
            List<Process> children = new List<Process>();
            ManagementObjectSearcher mos = new ManagementObjectSearcher(String.Format("Select * From Win32_Process Where ParentProcessID={0}", process.Id));
    
            foreach (ManagementObject mo in mos.Get())
            {
                children.Add(Process.GetProcessById(Convert.ToInt32(mo["ProcessID"])));
            }
    
            return children;
        }
    }
    
    0 讨论(0)
提交回复
热议问题