2

我有一個名爲MyScript的Python腳本(基於RHEL的unix類型),它有兩個函數,名爲A和B.我希望它們在不同的獨立進程中運行(分離B和A):故意在python中創建一個孤兒進程

  • 開始腳本的MyScript
  • 執行功能的
  • 產生一個新的過程中,從功能的傳遞數據到B
  • 雖然函數B運行時,繼續功能的
  • 當功能A完成,即使B仍在運行,退出MyScript

我以爲我應該使用多處理來創建一個守護進程,但documentation表明這不是正確的用例。所以,我決定生成一個子進程和子進程(孩子的孩子),然後強制孩子終止。雖然這種解決方法似乎有效,但看起來確實很難看。

你能幫我把它變成pythonic嗎?子流程模塊是否有一個可以在函數上運行的方法?下面的示例代碼。

import multiprocessing 
import time 
import sys 
import os 

def parent_child(): 
    p = multiprocessing.current_process() 
    print 'Starting parent child:', p.name, p.pid 
    sys.stdout.flush() 
    cc = multiprocessing.Process(name='childchild', target=child_child) 
    cc.daemon = False 
    cc.start() 
    print 'Exiting parent child:', p.name, p.pid 
    sys.stdout.flush() 

def child_child(): 
    p = multiprocessing.current_process() 
    print 'Starting child child:', p.name, p.pid 
    sys.stdout.flush() 
    time.sleep(30) 
    print 'Exiting child child:', p.name, p.pid 
    sys.stdout.flush() 

def main(): 
    print 'starting main', os.getpid() 
    d = multiprocessing.Process(name='parentchild', target=parent_child) 
    d.daemon = False 
    d.start() 
    time.sleep(5) 
    d.terminate() 
    print 'exiting main', os.getpid() 

main() 
+0

您使用的是什麼操作系統? – Keith

+0

@凱斯,剛剛更新了這個問題。類Unix。 – Peter

回答

2

這裏只是其中移動功能集成到一個單一的通話spawn_detached(callable)原密碼隨機版本。即使在程序退出後,它仍然保持分離的進程運行:

import time 
import os 
from multiprocessing import Process, current_process 

def spawn_detached(callable): 
    p = _spawn_detached(0, callable) 
    # give the process a moment to set up 
    # and then kill the first child to detach 
    # the second. 
    time.sleep(.001) 
    p.terminate() 

def _spawn_detached(count, callable): 
    count += 1 
    p = current_process() 
    print 'Process #%d: %s (%d)' % (count, p.name, p.pid) 

    if count < 2: 
     name = 'child' 
    elif count == 2: 
     name = callable.func_name 
    else: 
     # we should now be inside of our detached process 
     # so just call the function 
     return callable() 

    # otherwise, spawn another process, passing the counter as well 
    p = Process(name=name, target=_spawn_detached, args=(count, callable)) 
    p.daemon = False 
    p.start() 
    return p 

def operation(): 
    """ Just some arbitrary function """ 
    print "Entered detached process" 
    time.sleep(15) 
    print "Exiting detached process" 


if __name__ == "__main__": 
    print 'starting main', os.getpid() 
    p = spawn_detached(operation) 
    print 'exiting main', os.getpid() 
+0

該程序不會退出。嘗試運行[我的答案中的代碼](http://stackoverflow.com/a/13096616/4279)。它顯示了在主線程退出時加入了子進程(帶有.daemon = False)。或者你可以在'top'中尋找pid(用於你的代碼)。 – jfs

+0

@ J.F.Sebastian:我不確定你在說什麼。該程序立即退出到shell並且原始PID不再存在。只有'運營'PID在那裏。 – jdi

+0

你是對的。該pid不在那裏。 – jfs