有没有办法检查pid是否对应于有效的进程?我从os.getpid()
以外的其他来源获取pid,我需要检查机器上是否不存在具有该pid的进程。
我需要它在Unix和Windows中可用。我还在检查PID是否未被使用。
发布于 2009-02-20 04:31:14
如果pid未运行,则向pid发送信号0将引发OSError异常,否则不执行任何操作。
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
发布于 2011-08-04 19:08:51
mluebke代码不是100%正确的;kill()还会引发EPERM (拒绝访问),在这种情况下,这显然意味着存在一个进程。这应该是可行的:
(根据Jason R.Coombs评论编辑)
import errno
import os
def pid_exists(pid):
"""Check whether pid exists in the current process table.
UNIX only.
"""
if pid < 0:
return False
if pid == 0:
# According to "man 2 kill" PID 0 refers to every process
# in the process group of the calling process.
# On certain systems 0 is a valid PID but we have no way
# to know that in a portable fashion.
raise ValueError('invalid PID 0')
try:
os.kill(pid, 0)
except OSError as err:
if err.errno == errno.ESRCH:
# ESRCH == No such process
return False
elif err.errno == errno.EPERM:
# EPERM clearly means there's a process to deny access to
return True
else:
# According to "man 2 kill" possible error values are
# (EINVAL, EPERM, ESRCH)
raise
else:
return True
除非你使用pywin32、ctypes或C扩展模块,否则你不能在Windows上这样做。如果您不介意依赖于外部库,那么可以使用psutil
>>> import psutil
>>> psutil.pid_exists(2353)
True
发布于 2013-11-25 15:05:53
在Python 3.3+中,您可以使用异常名称而不是errno常量。Posix version
import os
def pid_exists(pid):
if pid < 0: return False #NOTE: pid == 0 returns True
try:
os.kill(pid, 0)
except ProcessLookupError: # errno.ESRCH
return False # No such process
except PermissionError: # errno.EPERM
return True # Operation not permitted (i.e., process exists)
else:
return True # no error, we can send a signal to the process
https://stackoverflow.com/questions/568271
复制相似问题