python子进程:在信号处理程序中查找哪个子进程终止

时间:2015-12-04 03:13:51

标签: python subprocess signals

我有一个python脚本,它使用subprocess.Popen启动多个命令。我添加了一个信号处理程序,如果一个孩子退出就会调用它。我想检查哪个孩子被终止了。我可以通过迭代所有孩子来做到这一点:

#!/usr/bin/env python
import subprocess
import signal

procs = []

def signal_handler(signum, frame):
    for proc in procs:
        proc.poll()
        if proc.returncode is not None:
            print "%s returned %s" % (proc.pid, proc.returncode)
            procs.remove(proc)

def main():
    signal.signal(signal.SIGCHLD, signal_handler)
    procs.append(subprocess.Popen(["/bin/sleep", "2"]))
    procs.append(subprocess.Popen(["/bin/sleep","5"]))
    # wait so the main process does not terminate immediately
    procs[1].wait()

if __name__ == "__main__":
    main()

我想避免查询所有子进程。有没有办法在信号处理程序中确定哪个孩子终止了?

1 个答案:

答案 0 :(得分:1)

您可以使用multiprocessing获得类似的结果。如果您不想生成额外的进程,可以使用threading包。它有几乎完全相同的界面。基本上,每个subprocess调用都会在新进程中发生,然后启动sleep进程。

import subprocess
import multiprocessing

def callback(result):
    # do something with result
    pid, returncode = result
    print pid, returncode


def call_process(cmd):
    p = subprocess.Popen(cmd)
    p.wait()
    return p.pid, p.returncode


def main():
    pool = multiprocessing.Pool()
    pool.apply_async(call_process, [["/bin/sleep", "2"]], callback=callback)
    pool.apply_async(call_process, [["/bin/sleep", "5"]], callback=callback)
    pool.close()
    pool.join()


main()