Python和命名管道,重新打开之前如何等待?

时间:2015-09-16 22:18:35

标签: python concurrency named-pipes

我正在使用命名管道开发两种方式的IPC,但我遇到了这种并发问题:

writer.py:

with open("fifo", "w") as f:
   f.write("hello")
with open("fifo", "w") as f:
   f.write("hello2")

reader.py:

with open("fifo", "r") as f:
   f.read()
with open("fifo", "r") as f:
   f.read()
问题是:

writer opens the fifo
reader opens the fifo
writer writes "hello"
writer closes the fifo
writer opens the fifo
writer writes "hello2"
reader reads "hellohello2"
writer closes the fifo
reader closes the fifo
reader opens the fifo
reader hangs up

是否有办法(不使用协议来控制)同步并强制写入者等待读者在重新打开之前关闭了fifo?

1 个答案:

答案 0 :(得分:0)

唯一可靠的方法是使用终止字符编写器端,并一次读取一个字符,直到终止字符阅读器端。

所以它可能是这样的:

writer.py:

with open("fifo", "w") as f:
   f.write("hello\n")
with open("fifo", "w") as f:
   f.write("hello2\n")

reader.py

def do_readline(f):
    line = ""
        while True:

        c = f.read(1)
        line += c
        if c == '\n':
            break
    return line

with open("fifo", "r") as f:
   do_readline(f)
with open("fifo", "r") as f:
   do_readline(f)