How to kill a python child process created with subprocess.check_output() when the parent dies?

后端 未结 5 1827
再見小時候
再見小時候 2020-11-27 05:17

I am running on a linux machine a python script which creates a child process using subprocess.check_output() as it follows:

subprocess.check_output([\"ls\",         


        
5条回答
  •  隐瞒了意图╮
    2020-11-27 06:18

    Your problem is with using subprocess.check_output - you are correct, you can't get the child PID using that interface. Use Popen instead:

    proc = subprocess.Popen(["ls", "-l"], stdout=PIPE, stderr=PIPE)
    
    # Here you can get the PID
    global child_pid
    child_pid = proc.pid
    
    # Now we can wait for the child to complete
    (output, error) = proc.communicate()
    
    if error:
        print "error:", error
    
    print "output:", output
    

    To make sure you kill the child on exit:

    import os
    import signal
    def kill_child():
        if child_pid is None:
            pass
        else:
            os.kill(child_pid, signal.SIGTERM)
    
    import atexit
    atexit.register(kill_child)
    

提交回复
热议问题