我正在使用多处理模块(multiprocessing module)编写一个应用程序(linux),该模块生成了几个子模块。当一个孩子死了,我可以用如下方法从父母那里检测出来:
process = multiprocessing.Process(...)
if process.is_alive():
print "Process died"
不过,我也希望能够从孩子身上检测出父母是否还活着,如果有人去清理并杀死-9的父母进程。
从上面的示例中,我可以使用以下任一项获取父ID:
process._parent_pid
或:
os.getppid()
但是我找不到一个简单的方法来获得这个过程的状态。我不想用subprocess为grep/regex编写ps列表。有更干净的方法吗?
最佳答案
您可以将父进程的id与1
进行比较;如果是1
则可以推断父进程已终止,因为子进程现在将init
进程(pid 1)作为父进程。
import os
import time
from multiprocessing import Process
def subprocess():
while True:
ppid = os.getppid()
print "Parent process id:", ppid
if ppid == 1:
print "Parent process has terminated"
break
time.sleep(1)
p = Process(target=subprocess)
p.start()
关于python - Python多处理。您如何从 child 那里获得 parent 的身份?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28597692/