2012-04-13 80 views
2

我見過的幾個問題,如這一個,而是試圖檢查的各種變種如果孩子還活着,並退出子進程後,我簡化了這個問題,它仍然是行不通的。Python的派生進程不會死

我在用sys.exit(0)退出分支進程時出錯了嗎? 是否有另一種殺死它的方法。事情是,我不能讓父母殺死進程,因爲它不知道他們什麼時候完成工作。

起初我以爲這是因爲在退出之前執行了一個系統命令(Python run system command and then exit... won't exit),但我甚至在簡化版本中刪除了它,因爲給定的解決方案也不起作用。

下面是一個例子:

import sys 
import os 
import time 

children = [] 

for i in range(0,3):  
    pid = os.fork() 

    if pid == -1: 
     continue 
    elif pid == 0: 
     # Do work... 
     print 'Child %d spawned' % os.getpid() 
     sys.exit(0)  
    else: 
     children.append(pid) 

time.sleep(5) 
for pid in children: 
    proc_path = '/proc/%d' % pid 
    if not os.path.exists(proc_path): 
     print 'Child %d is dead' % pid 
    else: 
     print 'Child %d is alive' % pid 

此打印:

Child 27636 spawned 
Child 27637 spawned 
Child 27638 spawned 
Child 27636 is alive 
Child 27637 is alive 
Child 27638 is alive 

但子進程應該是死了。

在這種情況下是什麼導致這些進程成爲殭屍?

回答

4

您必須爲子進程wait()。爲孩子

import sys 
import os 
import time 

children = [] 

for i in range(0,3):  
    pid = os.fork() 

    if pid == -1: 
     continue 
    elif pid == 0: 
     # Do work... 
     print 'Child %d spawned' % os.getpid() 
     sys.exit(0)  
    else: 
     children.append(pid) 

time.sleep(5) 

# ADD NEXT TWO LINES: 
for pid in children: 
    os.waitpid(pid, 0) 

for pid in children: 
    proc_path = '/proc/%d' % pid 
    if not os.path.exists(proc_path): 
     print 'Child %d is dead' % pid 
    else: 
     print 'Child %d is alive' % pid 

父母必須wait()

請添加以下代碼行把事情糾正。詳情請參閱man 2 wait

在Python可以處理這些事情與subprocess模塊。

+0

謝謝。這工作,我將不得不添加更多的邏輯,但沒關係。 – JayLev 2012-04-13 11:28:03

2

對於孩子從PID表中消失,你需要在父母的身邊wait()

n_still_children_alive = len(children) 
while n_still_children_alive > 0: 
    pid, status = os.wait() 
    print "Child %d died and joined" % pid 
    n_still_children_alive -= 1 

如果你想玩弄在Python多,你多用multiprocessing module,而不是使用os模塊的更好。

+0

謝謝。我通常使用多處理,這就是爲什麼我從來沒有這個問題。但是現在我被Python 2.5所困住了。 – JayLev 2012-04-13 11:26:32