I have a program that triggers Python timers to spawn subprocesses. These subprocesses should be terminated once my program is terminated or killed. In order to do that, I'm using the "prctl hack", that sets which signal a child should receive once its parent dies. The undesired behaviour I get is: even though my main process is running, the children get killed. The following code recreates the problem:
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)
You can notice that, before the threads die, the sleep processes are still running. After the timer threads die, its respective subprocess dies as well, even with the main thread alive.