I want to kill child processes created by Popen when I send SIGTERM, SIGINT or SIGKILL to the parent process. For this I am using the following code which was suggested by this StackOverflow question's answers Here is the code which uses Ctypes to catch the signals and create this callable in child processes:
import signal
import ctypes
libc = ctypes.CDLL("libc.so.6")
def set_pdeathsig(sig = signal.SIGTERM):
def callable():
return libc.prctl(1, sig)
return callable
p = subprocess.Popen(args, preexec_fn = set_pdeathsig(signal.SIGTERM))
I have also read in the documentation of the subprocess that using preexec_fn can be dangerous, but I don't understand what can go wrong. So can you bring an example where this will cause a problem and is the following way of killing child processes acceptable? Is there any nicer way to do this?