子进程 pid 与 ps 输出不同
为什么子进程 pid (Popen.pid
) 的值与 ps
命令返回的值不同?
当 ps
从 python 内部(使用 subprocess.call()
)和另一个终端调用时,我注意到了这一点。
下面是一个要测试的简单 python 文件:
#!/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
通常 ps
报告的 pid 比 Popen.pid
报告的 pid 大 1 或 2。
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
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
因为该命令是在
shell=True
下运行的,所以 subprocess 返回的 pid 是用于运行该命令的 shell 进程的 pid。Because the command is run with
shell=True
, the pid returned by subprocess is that of the shell process used to run the command.