2013-06-27 27 views
1

我正在嘗試製作一個簡單的程序,它將啓動一個子進程,該進程會將一個字符串寫入管道,而父進程會計數,直到它從管道獲取字符串。然而,我的問題是,程序運行時,它不會計數或不會停止計數。我想知道如何檢查子進程是否仍在運行,並取決於計數循環的結果。當子進程結束時斷開循環

import os, time 

pipein, pipeout = os.pipe() 

def child(input, pipeout): 
    time.sleep(2) 
    msg = ('child got this %s' % input).encode() 
    os.write(pipeout, msg) 

input = input() 

pid = os.fork() 
if pid: 
    i = 0 
    while True: 
     print(i) 
     time.sleep(1) 
     i += 1 
     try: 
      os.kill(pid, 0) 
     except OSError: 
      break 
    line = os.read(pipein, 32) 
    print(line) 
else: 
    child(input, pipeout) 

回答

1

您應該使用subprocess模塊,然後就可以調用poll()

使用popen.poll()

Explained here

if Popen.poll() is not None: 
    //child process has terminated 

[編輯]:

「控制輸入和輸出的唯一方法並且還檢索返回碼是使用子流程模塊;這僅適用於Unix。」

Source

+0

'poll'將返回None如果進程尚未終止,它的退出狀態,如果有,檢查'<0'是沒有意義的。 – mata

+0

好我沒有使用子進程,所以它不能真正幫助我 – Sebastian

+0

@mata終止進程的代碼是一個負數,你可以檢查一個特定的代碼,如果你想 – Stephan