我正在尝试创建一个简单的程序,它将启动一个子进程,该进程在父进程计数之前将一个字符串写入管道,直到它从管道中获取字符串。然而,我的问题是,当程序运行时,它将不计数或不会停止计数。我想知道如何检查子进程是否仍在运行,并且取决于计数循环的中断。
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)
答案 0 :(得分:1)
您应该使用subprocess
模块,然后拨打poll()
使用popen.poll()
if Popen.poll() is not None:
//child process has terminated
[编辑]:
“控制输入和输出流以及检索返回代码的唯一方法是使用子进程模块;这些只能在Unix上使用。”