我有一个python循环,它从多个子进程读取数据(没有阻塞)。有时我必须给那个子进程写信。第一次写入执行,但如果我再次执行非阻塞读取然后再写入子进程,第二次写入似乎永远不会通过到子进程。在
我相信如果我执行一个定期的块读(进程.stderr.readline()),将进行第二次读取。有什么帮助吗?在
# 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 ''
read: first write
//nothing else
stdin
在C中是行缓冲的。您可能需要在子进程中禁用缓冲才能使其工作。您还需要添加一个process.stdin.flush()
,以确保不会在writer端得到缓冲。在相关问题 更多 >
编程相关推荐