【发布时间】:2018-02-22 01:36:41
【问题描述】:
我有一个程序可以触发 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,这只是之前测试的代码。那不应该在那里。如果我删除它,问题仍然存在。
标签: python python-3.x subprocess python-multithreading