在非阻塞读取之后写入子进程两次

2024-04-20 05:49:31 发布

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

我有一个python循环,它从多个子进程读取数据(没有阻塞)。有时我必须给那个子进程写信。第一次写入执行,但如果我再次执行非阻塞读取然后再写入子进程,第二次写入似乎永远不会通过到子进程。在

我相信如果我执行一个定期的块读(进程.stderr.readline()),将进行第二次读取。有什么帮助吗?在

Python循环

# create mock process
childprocesses = []
p = subprocess.Popen(['./cprogram'], 
    stdin=subprocess.PIPE, 
    stdout=subprocess.PIPE, 
    stderr=subprocess.PIPE)
childprocesses.append(p)
loop_4eva()

# the loop
def loop_4eva():
    for process in childprocesses:
        if(process.poll() is None):
            process.stdin.write("first write\n")
            output = non_block_read(process.stderr).strip()
            print output
            process.stdin.write("second write\n")
            output = non_block_read(process.stderr).strip()
            print output


def non_block_read(output):
    fd = output.fileno()
    fl = fcntl.fcntl(fd, fcntl.F_GETFL)
    fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
    try:
            return output.readline()
    except:
            return ''

子进程(c程序)

^{pr2}$

输出(python打印…)

read: first write
//nothing else


Tags: loopreadoutput进程stderrstdinblockprocess
1条回答
网友
1楼 · 发布于 2024-04-20 05:49:31

stdin在C中是行缓冲的。您可能需要在子进程中禁用缓冲才能使其工作。您还需要添加一个process.stdin.flush(),以确保不会在writer端得到缓冲。在

相关问题 更多 >