Search code examples
pythonlinuxprocesspopenpid

Get Process Information After Termination


I need some information about one child process after termination.

Such as utime and VMPeak in /proc like this:

proc.wait()
with open('/proc/%d/stat' % proc.pid, "r") as f:
    stat = str(f.read()).strip().split()
    # 14th column is utime, 15th column is stime (man 5 proc)                  
    cpu_time = int(stat[14]) + int(stat[15])
    return cpu_time

But Python Popen.wait() released PID, so I will get:

No such file or directory

Can I get that after termination, or wait for termination without releasing PID ? (I mean wait for termination without invoke wait() which will release all resource.)

I'd be grateful if you could help me. Thanks!


Solution

  • Quoting from man 5 proc:

    /proc/[pid]
    There is a numerical subdirectory for each running process; the subdirectory is named by the process ID.

    A terminated process is no longer running, and its /proc/[pid] directory (including the stat file), is no longer going to be there.

    If it was going to be there, you can just store the PID in a variable before you call proc.wait():

    pid = proc.pid
    proc.wait()
    with open('/proc/%d/stat' % pid, "r") as f:
    

    There is no 'just before termination' event; subprocess waits, then reaps the exit code.

    You could do your own waiting with os.wait4() instead:

    pid, status, resources = os.wait4(proc.pid, 0)
    cpu_time = resources.ru_utime + resources.ru_stime
    

    resources is a named tuple, see resource.getrusage() for a list of what names it supports. Both .ru_utime and .ru_stime are floating point values.