繁体   English   中英

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

[英]Python and named pipes, how to wait before re-open?

我正在开发使用命名管道的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?

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

所以可能是这样的:

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM