問題描述
我正在開發渲染農場,我需要我的客戶能夠啟動渲染器的多個實例,而不會阻塞,以便客戶端可以接收新命令.我的工作正常,但是在終止創建的進程時遇到問題.
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
")
try:
p.terminate()
except Exception,e:
print str(e)
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;有更簡單的代碼(不依賴于 grep)可用于 linux.
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)
這篇關于如何終止多處理池進程?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!