2012-08-12 57 views

回答

2

我不知道Python,但我覺得你這樣做,就像你做它在C,通過檢查的fork()返回值:如果你想在孩子執行一些代碼

child_pid = os.fork() 
if child_pid == 0: 
    print "This is the child." 
    sys.exit(0) 
print "This is the parent." 
+0

通過這種方式,子進程也會打印出「This is the parent。」。我如何確保「fork block」之外的任何內容不會在子進程*中執行。 – satoru 2012-08-12 11:18:46

+0

不,這是父母打印「這是父母」。子進入該行之前調用'sys.exit(0)'。它是通過退出塊的最後一個孩子,你確保孩子除了塊之外什麼都不執行。 – 2012-08-12 11:24:39

3

流程,使用multiprocessing模塊。下面是一個例子,從文檔:

from multiprocessing import Process 

def f(name): 
    print 'hello', name 

if __name__ == '__main__': 
    p = Process(target=f, args=('bob',)) 
    p.start() 
    p.join() 

這個例子說明如何使用函數˚F可以在子進程中執行。

相關問題