Search code examples
pythonpsutil

psutil/subprocess return code when process killed


I replaced some use of Python subprocess.Popen instances with psutil.Popen instances and expected the behaviour to remain the same.

The psutil docs for Popen state:

A more convenient interface to stdlib subprocess.Popen. It starts a sub process and deals with it exactly as when using subprocess.Popen but in addition it also provides all the methods of psutil.Process class in a single interface.

I have found that the return code when terminating a process is not the same, as demonstrated by the sample below.

>>> import subprocess
>>> p = subprocess.Popen('sleep 100', shell=True)
>>> p.kill()
>>> p.wait()
-9
>>> 
>>> import psutil
>>> p = psutil.Popen('sleep 100', shell=True)
>>> p.kill()
>>> p.wait()
9
>>> 
>>> print sys.version
2.7.3 (default, Aug 28 2012, 13:02:46) 
[GCC 4.4.6 20110731 (Red Hat 4.4.6-3)]
>>> print psutil.__version__
2.1.1

What are the POSIX guarantees on exit codes when a process is terminated? Are both the above return codes valid?


Solution

  • POSIX exit codes have values 0-255. POpen's retcode isn't exactly the same as the process' exit code, in that POpen will sometines use the -ve code. The POpen docs are quite explicit as to when that can/will happen:

    Ref documentation: https://docs.python.org/2/library/subprocess.html#subprocess.Popen.returncode Ref this question How to get exit code when using Python subprocess communicate method?

    However, the psutil docs don't mention that at all: https://code.google.com/p/psutil/wiki/Documentation#Classes (see the wait(timeout=None) section).

    I guess it's arguable as to which is 'correct', but if psutil is supposed to follow the same interface as POpen, then I think this is probably a bug/missing feature.