终止程序退出时在线程中运行的子进程

问题描述:

根据对此问题接受的答案:python-subprocess-callback-when-cmd-exits我正在独立线程中运行子进程,并在子进程完成后执行可调用。一切都很好,但问题是,即使运行的线程作为守护程序,子进程也继续程序正常退出后运行或它是由kill -9,按Ctrl + C,等杀...终止程序退出时在线程中运行的子进程

下面是一个很简单的例子(2.7运行):

import threading 
import subprocess 
import time 
import sys 


def on_exit(pid): 
    print 'Process with pid %s ended' % pid 

def popen_with_callback(cmd): 

    def run_in_thread(command): 
     proc = subprocess.Popen(
      command, 
      shell=False 
     ) 
     proc.wait() 
     on_exit(proc.pid) 
     return 

    thread = threading.Thread(target=run_in_thread, args=([cmd])) 
    thread.daemon = True 
    thread.start() 
    return thread 

if __name__ == '__main__': 
    popen_with_callback(
     [ 
      "bash", 
      "-c", 
      "for ((i=0;i<%s;i=i+1)); do echo $i; sleep 1; done" % sys.argv[1] 
     ]) 
    time.sleep(5) 
    print 'program ended' 

如果主线程持续时间比子都不再是罚款:

(venv)~/Desktop|➤➤ python testing_threads.py 3 
> 0 
> 1 
> 2 
> Process with pid 26303 ended 
> program ended 

如果主线程持续不到子进程,子进程继续运行直到它最终挂起:

(venv)~/Desktop|➤➤ python testing_threads.py 8 
> 0 
> 1 
> 2 
> 3 
> 4 
> program ended 
(venv)~/Desktop|➤➤ 5 
> 6 
> 7 
# hanging from now on 

如何在主程序完成或终止时终止子进程?我试图在proc.wait之前使用atexit.register(os.kill(proc.pid, signal.SIGTERM)),但是当运行子进程的线程退出时它实际上执行,而不是在线程退出时执行。

我也在考虑为父pid进行轮询,但由于proc.wait的情况,我不确定如何实现它。

理想的结果将是:

(venv)~/Desktop|➤➤ python testing_threads.py 8 
> 0 
> 1 
> 2 
> 3 
> 4 
> program ended 
> Process with pid 1234 ended 

使用Thread.join方法,其中块主线程,直到该线程退出:

if __name__ == '__main__': 
    popen_with_callback(
     [ 
      "bash", 
      "-c", 
      "for ((i=0;i<%s;i=i+1)); do echo $i; sleep 1; done" % sys.argv[1] 
     ]).join() 
    print 'program ended'