views:

364

answers:

2

Is there a way to get the Process.TotalProcessorTime that reflects a process PLUS any processes that it has spawned?

Alternatively, how can I verify that the process (or it's descendants) are still "actively" running?


My app is spawning an external process and waiting for it to exit. With sample data it takes 5-20 minutes to complete; I don't have a guess for a reasonable maximum timeout. So my app checks the Process.TotalProcessorTime value on the other process at intervals, to ensure that it keeps rising.

This works fine, but I've discovered that the process is simply a "wrapper" that spawns a sub-process, which in turn spawns a handful of other sub-process that consume all of the CPU time.

And I've found that TotalProcessorTime returns only a small fraction of a second after several minutes of 100% CPU utilization.

A: 

You can use a performance counter to retrieve the parent process like this:

PerformanceCounter pc = new PerformanceCounter("Process", 
    "Creating Process Id", " windbg");
Process p = Process.GetProcessById((int)pc.RawValue);

Having that information you can monitor processes in the system, maintain a structure of the whole process tree and calculate TotalProcessorTime for tree. Hope that helps

bbmud
A: 

I haven't implemented this, but have figured out how it might work. It's tedious but not all that complicated.

  1. Spawn a background thread that every few seconds will:

    • Build the process tree (see this answer for a simplified version of the code),
    • Terminate (the monitor thread) if the process has exited.
    • Maintain a hash of the accumulated CPU Usage by PID,
    • Maintain a sum of all values by all processes,
    • Maintain the difference of the sum from the last time the thread fired.
  2. This should allow the calling code to easily check that the process (tree) is not hung (I/O bound processes might have problems here, but that doesn't apply to my case).

None of this seems difficult, with the possible exception of getting CPU usage of a process not spawned (directly) by the monitoring thread.

I'll update this answer if/when I implement the code, but it may be a long time.

NVRAM