2012-04-13 5 views
2

私はこのようないくつかの質問を見ましたが、子供が生きて子供のプロセスを終了しているかどうかを確認する様々なバリエーションを試した後、私は問題を単純化し、それでも動作しません。Pythonフォークされたプロセスは死ぬことはありません

私はsys.exit(0)でforkしたプロセスを終了するのに間違っていますか? それを殺す別の方法がありますか?問題は、親がプロセスを終了させることはできません。なぜなら、プロセスが終了した時点を知らないからです。

私は、システムコマンドを実行する前に(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をご覧ください。

あなたはsubprocessモジュールでこれらのことを処理できます。

+0

ありがとうございました。これは動作しますが、ロジックを追加する必要がありますが、それは問題ありません。 – JayLev

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

関連する問題