2014-04-01 54 views
8

我正在使用多进程模块进行并行处理。 贝娄代码片段在X位置搜索字符串文件名并返回找到该字符串的文件名。 但在某些情况下,它需要很长时间来搜索过程,所以我试图杀死搜索过程需要超过300秒。为此,我使用超时== 300作为给定的波纹管,这杀死了搜索过程,但它剂量杀死子进程由波纹管代码产生。自动杀死进程和多进程子进程池

我试图找到多种方式,但没有成功:/

我如何能杀死从池父进程及其子进程来吗?在Process Explorer的

import os 
from multiprocessing import Pool 

def runCmd(cmd): 
    lresult = os.popen(cmd).read() 
    return lresult 

main(): 
    p = Pool(4) 
    data_paths = [list of paths of store data] 
    search_cmds = [ "SearchText.exe %s < %s"%(data_path, filename) for data_path in data_paths ] 
    results = [p.apply_async(runCmd, (cmd,), callback = log_result) for cmd in search_cmds] 
    try: 
     for result in results: 
      root.append(result.get(timeout=300)) 
     #rool holds the result of search process 
    except TimeoutError: 
     for c in multiprocessing.active_children(): 
      print '----->',c.pid 
      os.kill(c.pid, signal.SIGTERM) 
    p.close() 
    p.join() 

if __name__ == '__main__': 
    main() 

进程树:

cmd.exe 
------python.exe 
----------------python.exe 
--------------------------cmd.exe 
---------------------------------SearchText.exe 
----------------python.exe 
--------------------------cmd.exe 
---------------------------------SearchText.exe 
----------------python.exe 
--------------------------cmd.exe 
---------------------------------SearchText.exe 
----------------python.exe 
--------------------------cmd.exe 
---------------------------------SearchText.exe 

上面的代码片断dosnt杀子进程

--------------------------cmd.exe 
---------------------------------SearchText.exe 
--------------------------cmd.exe 
---------------------------------SearchText.exe 
--------------------------cmd.exe 
---------------------------------SearchText.exe 
--------------------------cmd.exe 
---------------------------------SearchText.exe 

论文子搜索过程中保留,这些子进程也被杀。

请公会。

感谢

回答

7

我能够使用psutil模块来解决我的问题

对波纹管后

找到解决方案:

import psutil, os 

def kill_proc_tree(pid, including_parent=True):  
    parent = psutil.Process(pid) 
    for child in parent.get_children(recursive=True): 
     child.kill() 
    if including_parent: 
     parent.kill() 

me = os.getpid() 
kill_proc_tree(me) 

https://stackoverflow.com/a/4229404/420557

+3

get_children不存在了该方法被称为[children](http://pythonhosted.org/psutil/#psu) til.Process.children) – user37203

+0

我使用守护进程,所以这种方法正是我所期待的。 – crsuarezf