关闭主进程时Python关闭子进程

时间:2011-11-16 10:41:37

标签: python fork parallel-processing signals kill

我有一个主进程,它会分叉许多子进程。我希望能够在主进程获取kill信号时终止这些子进程。理想情况下,我想要做的事情是:

def handler(signum, frame, pid_list):
    log('Killing Process')
    for pid in pid_list:
       os.kill(pid, signal.SIGTERM)
       os.waitpid(pid, 0)         # need
    sys.exit()

if __name__ == "__main__":
    <code that creates child processes, pids>
    signal.signal(signal.SIGTERM, handler(pid_list))

但当然,这不起作用......有什么建议吗?

2 个答案:

答案 0 :(得分:3)

作为@tony suggested,您可以在使用daemon=True模块创建的子进程上设置multiprocessing标志。要在python2.4上安装它,请输入:pip install multiprocessing

如果主进程被信号杀死,子进程将不会终止,因此您需要提供适当的信号处理程序:

#!/usr/bin/env python
import logging, signal, sys, time
import multiprocessing as mp # `pip install multiprocessing` on Python <2.6

class AddProcessNameFilter(logging.Filter):
    """Add missing on Python 2.4 `record.processName` attribute."""
    def filter(self, r):
        r.processName = getattr(r, 'processName', mp.current_process().name)
        return logging.Filter.filter(self, r)

def print_dot():
    while True:
        mp.get_logger().info(".")
        time.sleep(1)

def main():
    logger = mp.log_to_stderr()
    logger.setLevel(logging.INFO)
    logger.addFilter(AddProcessNameFilter()) # fix logging records

    # catch TERM signal to allow finalizers to run and reap daemonic children
    signal.signal(signal.SIGTERM, lambda *args: sys.exit(-signal.SIGTERM))

    # create daemonic child processes
    processes = [mp.Process(target=print_dot) for _ in range(2)]
    for p in processes:
        p.daemon = True
        p.start()    
    print_dot()

if __name__=="__main__":
    mp.freeze_support()
    main()

答案 1 :(得分:1)

创建子流程时使用this标志怎么样?