在Python中,不使用/proc文件系统,如何判断给定的PID是否正在运行?
假设我有一个 PID,例如 555。我想查看该 pid 是否正在运行或已完成。我可以检查 /proc/ 但我无法在生产环境中访问它。除了像打开“ps”管道这样的黑客行为之外,最好的方法是什么?
Say I have a PID, like 555. I want to see if that pid is running or has completed. I can check /proc/ but I don't have access to that in my production environment. What's the best way to do this, short of something hackish like opening a pipe to "ps"?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用
os.kill()
函数信号编号为 0。如果进程 pid 存在,则调用将成功,否则将引发OSError
异常:kill( 的文档2)
在我的系统上说:Use the
os.kill()
function with a signal number of 0. If the process pid exists, then the call will be successful, else it will raise anOSError
exception:The documentation for
kill(2)
on my system says:使用 Greg 提到的 os.kill() ,但要意识到,kill 系统调用不是测试进程是否存在,而是测试是否可以向进程发送终止消息。一种失败模式是进程不存在,另一种失败模式是您无权终止它。为了区分,你必须检查异常:
如果你知道你总是有权终止你正在检查的进程,那么这不是必需的,比如因为你以 root 身份运行,或者已知该进程在与检查它的进程相同的 UID。
Use
os.kill()
as mentioned by Greg, but realize that the kill system call tests not whether the process exists, but whether you can send a kill to the process. One failure mode is if the process doesn't exist, but another is that you do not have permission to kill it. To differentiate, you have to check the exception:This is not required if you know you are always going to have permission to kill the process you are checking for, say because you are running as root or the process is known to be running under the same UID as the process checking it.