我想在python中使用mutliprocessing模塊創建一個進程,但要確保它在創建子進程的進程退出後繼續運行。分離使用python多處理模塊啓動的子進程
我可以使用子進程模塊和Popen獲得所需的功能,但我想將我的代碼作爲函數運行,而不是腳本。我想這樣做的原因是爲了簡化創建pyro(python遠程對象)對象。我想在使用多處理的獨立進程中啓動pyro對象請求處理程序,但是當支持pyro對象的進程繼續運行時,我希望主進程退出。
我想在python中使用mutliprocessing模塊創建一個進程,但要確保它在創建子進程的進程退出後繼續運行。分離使用python多處理模塊啓動的子進程
我可以使用子進程模塊和Popen獲得所需的功能,但我想將我的代碼作爲函數運行,而不是腳本。我想這樣做的原因是爲了簡化創建pyro(python遠程對象)對象。我想在使用多處理的獨立進程中啓動pyro對象請求處理程序,但是當支持pyro對象的進程繼續運行時,我希望主進程退出。
我終於得到了我想要的東西。我很欣賞任何改進代碼的建議。
def start_server():
pyrodaemon = Pyro.core.Daemon()
#setup daemon and nameserver
#Don't want to close the pyro socket
#Need to remove SIGTERM map so Processing doesn't kill the subprocess
#Need to explicitly detach for some reason I don't understand
with daemon.DaemonContext(files_preserve=[pyrodaemon.sock],signal_map={signal.SIGTERM:None},detach_process=True):
while running:
pyrodaemon.handleRequests(timeout=1.0)
#when finished, clean up
pyrodaemon.shutdown()
def main():
p = Process(target=start_server)
p.daemon=True # Need to inform Process that this should run as a daemon
p.start()
time.sleep(3.0) # Important when running this program stand alone: Must wait long enough for start_server to get into the daemon context before the main program exits or Process will take down the subprocess before it detaches
do_other_stuff_not_in_the_daemon()
守護進程的詞在這裏被濫用;)*不要*設置Process.daemon爲真。這告訴多處理試圖在出口處殺死孩子(混淆吧?)。我想這就是爲什麼你需要捕獲SIGTERM並在上面的代碼中設置detach_process。 - http://docs.python.org/library/multiprocessing.html#multiprocessing.Process.daemon – JimB 2009-11-19 14:59:22
謝謝你的回覆。我最近遇到了這個解決方案,我同意。然而,python守護進程似乎是針對更標準的範例,其中一個程序有一個作爲守護進程啓動的函數,並且永遠不會返回。我願做線沿線的東西: 與daemon.DaemonContext(): some_daemon_loop() continue_with_this_function_after_daemon_has_launched() 我明白任何建議。 – glenn 2009-11-19 06:47:25
我之前並沒有真正看過pyro。粗略地看一下他們的代碼,「守護進程」類就像一個線程調度器,而不是一個單獨的進程;沒有代碼在哪裏分叉。 Pyro有一個包含守護進程真實守護進程功能的模塊。 – JimB 2009-11-19 14:40:02