简体   繁体   中英

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

I'm developing a two ways IPC using named pipes, but I've this concurrency problem :

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()

the problem is :

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

Is there a way (without using a protocol to control) to synchronize and force writer to wait that reader has closed the fifo too before re-opening ?

The only reliable way would be to use a terminating character writer side, and read one char at a time until the terminating character reader side.

So it could be something like:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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