3
我有一个程序触发Python定时器来产生子进程。一旦我的程序被终止或终止,这些子进程应该被终止。为了做到这一点,我使用了“prctl hack”,它设置了一旦其父母死亡,孩子应该接收哪个信号。我得到的不良行为是:即使我的主要过程正在运行,孩子们也会被杀死。下面的代码重现该问题:线程死时子进程死掉
from threading import Timer
import time
import os
import subprocess
import ctypes
import signal
def set_pdeathsig():
print("child PID: %d" % os.getpid())
print("child's parent PID: %d" % os.getppid())
prctl = ctypes.CDLL("libc.so.6").prctl
PR_SET_PDEATHSIG = 1
prctl(PR_SET_PDEATHSIG, signal.SIGTERM)
def thread1():
subprocess.Popen(['sleep', 'infinity'], preexec_fn=set_pdeathsig)
time.sleep(10)
print("thread 1 finished")
def thread2():
subprocess.Popen(['sleep', 'infinity'], preexec_fn=set_pdeathsig)
time.sleep(10)
print("thread 2 finished")
print("main thread PID: %d" % os.getpid())
t1 = Timer(1, thread1)
t2 = Timer(1, thread2)
t1.start()
t2.start()
time.sleep(100)
你可以注意到,线程死之前,该sleep
进程仍在运行。计时器线程死后,其各个子进程也会死掉,即使主线程还活着。
显然,你不要调用函数'os.setpgid' –
谢谢@TheophileDano,这只是以前的测试代码。那不应该在那里。如果我删除它,问题仍然存在。 –