python多处理池终止 [英] python multiprocessing pool terminate

查看:127
本文介绍了python多处理池终止的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理渲染场,我需要我的客户端能够启动渲染器的多个实例而不会阻塞,以便客户端可以接收新命令.我的工作正常,但是在终止创建的进程时遇到了麻烦.

I'm working on a renderfarm, and I need my clients to be able to launch multiple instances of a renderer, without blocking so the client can receive new commands. I've got that working correctly, however I'm having trouble terminating the created processes.

在全局级别,我定义了我的池(以便可以从任何函数访问它):

At the global level, I define my pool (so that I can access it from any function):

p = Pool(2)

然后我用apply_async调用渲染器:

I then call my renderer with apply_async:

for i in range(totalInstances):
    p.apply_async(render, (allRenderArgs[i],args[2]), callback=renderFinished)
p.close()

该函数完成,在后台启动进程,并等待新命令.我已经做了一个简单的命令,它将杀死客户端并停止渲染:

That function finishes, launches the processes in the background, and waits for new commands. I've made a simple command that will kill the client and stop the renders:

def close():
'close this client instance'
tn.write ("say "+USER+" is leaving the farm\r\n")
try:
    p.terminate()
except Exception,e:
    print str(e)
    sys.exit()
sys.exit()

似乎没有给出错误(它将显示错误),python终止了,但是后台进程仍在运行.谁能推荐一种更好的方法来控制这些已启动的程序?

It doesn't seem to give an error (it would print the error), the python terminates but the background processes are still running. Can anyone recommend a better way of controlling these launched programs?

推荐答案

找到了我自己问题的答案.主要问题是我在调用第三方应用程序而不是函数.当我调用子进程[使用call()或Popen()]时,它将创建一个新的python实例,其唯一目的是调用新应用程序.但是,当python退出时,它将杀死python的这个新实例并保持应用程序运行.

Found the answer to my own question. The primary problem was that I was calling a third-party application rather than a function. When I call the subprocess [either using call() or Popen()] it creates a new instance of python whose only purpose is to call the new application. However when python exits, it will kill this new instance of python and leave the application running.

解决方案是通过找到所创建的python进程的pid,获取该pid的子代并杀死它们来完成此难题.该代码特定于osx;在Linux上有更简单的代码(不依赖grep).

The solution is to do it the hard way, by finding the pid of the python process that is created, getting the children of that pid, and killing them. This code is specific for osx; there is simpler code (that doesn't rely on grep) available for linux.

for process in pool:
    processId = process.pid
    print "attempting to terminate "+str(processId)
    command = " ps -o pid,ppid -ax | grep "+str(processId)+" | cut -f 1 -d \" \" | tail -1"
    ps_command = Popen(command, shell=True, stdout=PIPE)
    ps_output = ps_command.stdout.read()
    retcode = ps_command.wait()
    assert retcode == 0, "ps command returned %d" % retcode
    print "child process pid: "+ str(ps_output)
    os.kill(int(ps_output), signal.SIGTERM)
    os.kill(int(processId), signal.SIGTERM)

这篇关于python多处理池终止的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆