Kill Child Process if Parent is killed in Python

前端 未结 3 1772
你的背包
你的背包 2020-12-09 15:50

I\'m spawning 5 different processes from a python script, like this:

p = multiprocessing.Process(target=some_method,args=(arg,))
p.start()

相关标签:
3条回答
  • 2020-12-09 16:24

    I've encounter the same problem myself, I've got the following solution:

    before calling p.start(), you may set p.daemon=True. Then as mentioned here python.org multiprocessing

    When a process exits, it attempts to terminate all of its daemonic child processes.

    0 讨论(0)
  • 2020-12-09 16:33

    The child is not notified of the death of its parent, it only works the other way.

    However, when a process dies, all its file descriptors are closed. And the other end of a pipe is notified about this, if it selects the pipe for reading.

    So your parent can create a pipe before spawning the process (or in fact, you can just set up stdin to be a pipe), and the child can select that for reading. It will report ready for reading when the parent end is closed. This requires your child to run a main loop, or at least make regular calls to select. If you don't want that, you'll need some manager process to do it, but then when that one is killed, things break again.

    0 讨论(0)
  • 2020-12-09 16:46

    If you have access to the parent pid you can use something like this

    import os
    import sys
    import psutil
    
    
    def kill_child_proc(ppid):
        for process in psutil.process_iter():
            _ppid = process.ppid()
            if _ppid == ppid:
                _pid = process.pid
                if sys.platform == 'win32':
                    process.terminate()
                else:
                    os.system('kill -9 {0}'.format(_pid))
    
    kill_child_proc(<parent_pid>)
    
    
    0 讨论(0)
提交回复
热议问题