Reputation: 1116
I have a process that calls:
p=multiprocessing.Process(target=func_a)
Then func_a
starts a subprocess:
subprocess.Popen(["nc", "-l", "-p", str(dport)], stdout=open(os.devnull, "w"))
My problem is that when I call p.terminate()
, it only kills the first child. p.terminate()
is a SIGKILL
so how could I make the subprocess die when I call p.terminate()
into the multiprocessing.Process
.
Upvotes: 1
Views: 1225
Reputation: 743
Register a handler with signal.signal like this:
#!/usr/bin/env python
import signal
import sys
def signal_handler(signal, frame):
#iterate over your subprocess and kill them
sys.exit(0)
signal.signal(signal."the signal", signal_handler)
print('Press Ctrl+C')
signal.pause()
More documentation on signal can be found here.
Upvotes: 1
Reputation: 1049
I found a way to make sure the sub-process is killed before the multiprocessing process is killed:
Create a class like this:
import subprocess
import multiprocessing
import time
import os
class MyProcess(multiprocessing.Process):
def __init__(self):
super(MyProcess,self).__init__()
self.q = multiprocessing.Queue()
def run(self):
# do something else
child = subprocess.Popen(['Your CMD'])
self.q.put(child.pid)
def MyTerminate(self):
pid = self.q.get()
os.kill(pid, 9) # works in windows and linux
# os.popen('taskkill.exe /pid '+str(pid)+' /F') # works only in windows
self.terminate()
Then you can use the function MyTerminate()
to kill the process safely.
For example:
def main():
mp = MyProcess()
mp.start()
time.sleep(1)
mp.MyTerminate()
The sub-process "child" will be killed after 1 second.
Upvotes: 1