简体   繁体   中英

Python: Killing children's children process

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 .

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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM