我需要检测孙进程的PID是否还活着。因为 multiprocessing.Process() 对象是不可pickle的(出于安全原因),所以我无法将其传递到进程层次结构并调用
process.is_alive()
,所以我需要传递PID并使用它。
以下代码成功识别出 PID 处于活动状态,但是当我手动终止该进程(在 Ubuntu 中使用 bash 中的
kill
)时,它会错误地继续将其检测为活动状态。另一方面,process.is_alive()
可以正常工作。如何仅使用 PID 可靠地检测 PID 状态?
import os
import time
from multiprocessing import Process
def pid_is_alive(pid):
try:
os.kill(pid, 0) # Send signal 0 to check if the process exists.
except ProcessLookupError:
return False
return True
def worker():
print("worker started")
print(os.getpid())
while True:
time.sleep(1)
print("worker running")
p = Process(target=worker)
p.start()
while True:
time.sleep(1)
# Check if the PID is alive
if pid_is_alive(p.pid):
print(f'PID {p.pid} is alive.')
else:
print(f'PID {p.pid} is not alive.')
# if p.is_alive():
# print("Process is alive")
# else:
# print("Process is not alive")
实际上,程序运行正常。
当您终止进程时,它会进入失效或僵尸状态,直到其父进程执行
wait()
。在此期间,PID 仍在使用中,并且 is_alive()
返回 True
- 如您所见,更具描述性的名称将是 PID_exists()
。
有多种选择:
fork
技术来孤立子进程。 PID 1 进程将成为新的父进程,并将为它wait
。在我看来,这是最简单的选择 - 如果您不介意失去退出状态。