自动终止multiprocessing Pool的进程和子进程

12

我正在使用multiprocessing模块进行并行处理。下面的代码片段在X位置中搜索字符串文件名并返回找到字符串的文件名。但是,在某些情况下,搜索过程需要很长时间,因此我尝试使用timeout == 300来终止搜索进程,但这样只能杀死搜索进程,无法杀死由下面的代码生成的子进程。我尝试了多种方式,但没有成功:/如何从池中杀死父进程以及其子进程?

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

上面的代码片段没有杀死子进程

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

这些子搜索进程被保留,这些子进程也会被结束。

请指导。

谢谢。

1个回答

11

我使用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://dev59.com/E3M_5IYBdhLWcg3wyWWt#4229404


3
get_children方法不再存在,该方法被称为[children](http://pythonhosted.org/psutil/#psutil.Process.children). - user37203
我使用了daemonize,所以这种方法正是我想要的。 - crsuarezf

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接