子进程 pid 与 ps 输出不同

发布于 2024-10-07 11:06:08 字数 823 浏览 0 评论 0原文

为什么子进程 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

情绪少女 2024-10-14 11:06:08

因为该命令是在 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文