本文介绍了如何检查 Python 中是否存在具有给定 pid 的进程?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法检查一个pid是否对应一个有效的进程?我从 os.getpid()
以外的其他来源获取 pid,我需要检查机器上是否不存在具有该 pid 的进程.
Is there a way to check to see if a pid corresponds to a valid process? I'm getting a pid from a different source other than from os.getpid()
and I need to check to see if a process with that pid doesn't exist on the machine.
我需要它在 Unix 和 Windows 中可用.我也在检查是否未使用 PID.
I need it to be available in Unix and Windows. I'm also checking to see if the PID is NOT in use.
推荐答案
如果 pid 未运行,则向 pid 发送信号 0 将引发 OSError 异常,否则不执行任何操作.
Sending signal 0 to a pid will raise an OSError exception if the pid is not running, and do nothing otherwise.
import os
def check_pid(pid):
""" Check For the existence of a unix pid. """
try:
os.kill(pid, 0)
except OSError:
return False
else:
return True
这篇关于如何检查 Python 中是否存在具有给定 pid 的进程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!