子进程完成时中断循环

2024-09-28 17:31:02 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图做一个简单的程序,它将启动一个子进程,在父进程计数的同时将字符串写入管道,直到它从管道中获取字符串。不过,当我的程序运行时,它要么停止,要么不计数。我想知道如何检查子进程是否仍在运行,并依赖于计数循环的中断。在

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)

Tags: 字符串childinput管道time进程osline