自动终止进程和多处理池的子进程

问题描述:

我正在使用多处理模块进行并行处理. 波纹管代码片段在X位置搜索字符串文件名,并返回找到该字符串的文件名. 但是在某些情况下,搜索过程会花费很长时间,因此我试图花费300秒以上的时间来终止搜索过程.为此,我使用timeout == 300作为给定的吼叫声,这杀死了搜索过程,但却使儿童丧命了通过下面的代码生成进程.

I am using multiprocessing module for parallel processing. Bellow code snippet search the string filename in X location and return the file name where the string found. But in some cases it take long time to search process so i was trying to kill the search process with take more than 300 seconds.For that i used timeout == 300 as given bellow , this kills the search process but it dosent kill the child process spawn by bellow code.

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

I tried to find multiple way but no success :/

我如何从Pool中杀死父进程及其子进程?

How can i kill parent process from Pool along with its child process ?

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

进程浏览器中的进程树:

Process Tree in Process Explorer :

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

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

above code snippet dosnt kill the child process

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

这些子搜索过程保留下来,这些子过程也被杀死.

Theses child search process retain , these child process also get killed .

请行会.

谢谢

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

I am able to solve my Issue using psutil module

在下面的文章中找到了解决方案:

Found solution on bellow post:

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