When I was writing a test for a program that runs as a daemon, I needed to kill it after a certain amount of time.
main process
|
|--- subprocess1
|--- subprocess2
|--- subprocess3
The subprocesses are started as follows.
# main.py
from multiprocessing import Process
ps = [
Process(target=hogehoge1),
Process(target=hogehoge2),
Process(target=hogehoge3),
]
for i in ps:
i.start()
Thing you want to do
Erase all subprocesses from another process in some way.
When I'm running it in the terminal, I can erase everything with this one, so I'll try it.
# other.py
import subprocess
from time import sleep
from signal import SIGINT
proc = subprocess.Popen(cmd)
sleep(5) #wait a little
proc.send_signal(SIGINT)
Only the parent disappears and the subprocesses remain.
This way it worked. The parent should have a signal (from the previous experiment), so let's remove the subprocess from the parent. Modify the parent file.
# main.py
from signal import SIGINT
import signal
def signalHandler(signal, handler) :
for i in ps:
i.terminate()
exit(0)
if __name__ == "__main__":
signal.signal(signal.SIGINT, signalHandler)
signal.signal(signal.SIGTERM, signalHandler)
Note: If you forget ʻexit (0)`, you will not be able to kill the parent process.
It's not good to multi-process in an atmosphere.
Recommended Posts