2011-11-16 52 views
2

我有一个主进程分叉了一些子进程。我希望能够在我的主进程获得终止信号时关闭这些子进程。理想情况下,我想要做一些沿线:Python在关闭主进程时关闭孩子

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)) 

但当然,这不工作......任何建议?

回答

3

As @tony suggested您可以在使用multiprocessing模块创建的子进程上设置daemon=True标志。要在python2.4上安装它,请键入:pip install multiprocessing。如果主要过程是由一个信号终止,所以你需要提供适当的信号处理

子进程不会被终止:@tony

#!/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

嗨J.F.,感谢关于pip'ing多处理器的指针;我没有打算在Centos上安装Python 2.6,但这可能只是一个窍门。我明天会放弃它并给你一些反馈。 –

+1

伟大的名字句柄,顺便说一句 –

+1

好的,所以这个效果很好,其他人尝试这样做的一些指针:1. p.daemon需要与signal.signal配对,p.daemon不只是做它的拥有。 2.在Centos上安装多处理:yum install python-pip gcc python-devel && pip-python install multiprocessing。再次感谢J.F. –

1

当您创建子流程时,使用this标志怎么办?

+1

嗯,谢谢你,但我没用过多处理类...从我可以看到它只能从python 2.6中得到,我在Centos 5.7下运行python 2.4.3。 –