Matthew
Matthew

Reputation: 403

subprocess pid different from ps output

Why is it that the subprocess pid (Popen.pid) has different value from that the ps command returns?

I've noticed this when ps called both from inside python (with subprocess.call()) and from another terminal.

Here's a simple python file to test:

#!/usr/bin/python3
'''
Test subprocess termination
'''

import subprocess

command = 'cat'

#keep pipes so that cat doesn't complain
proc = subprocess.Popen(command,
                    stdout=subprocess.PIPE,
                    stderr=subprocess.PIPE,
                    stdin=subprocess.PIPE,
                    shell=True)

print('pid = %d' % proc.pid)
subprocess.call("ps -A | grep -w %s" % command,
                    shell=True)

proc.terminate()
proc.wait()             # make sure its dead before exiting pytyhon

Usually the pid reported by ps is 1 or 2 more than that reported by Popen.pid.

Upvotes: 5

Views: 4970

Answers (1)

Ned Deily
Ned Deily

Reputation: 85055

Because the command is run with shell=True, the pid returned by subprocess is that of the shell process used to run the command.

Upvotes: 6

Related Questions