2015-09-16 94 views
0

我正在开发使用命名管道IPC一两种方式,但我这个并发问题:Python和命名管道,如何在重新打开之前等待?

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 

有没有一种方法(不使用协议来控制)s同步并强制作者等待读者在重新开放之前关闭了fifo?

+2

的参数'read'应该是要读取的字符数,不是一个字符串。我甚至不知道这是如何工作的,更不用说“不正确”了。对于这个问题,你真的用“os.mkfifo”创建了一个真正的命名管道,还是只打开一个名为'fifo'的随机文件? – ShadowRanger

+0

抱歉,有关'read()'的复制粘贴失败。其实我读到EOF(-1默认参数读取这个含义)。 我打开一个真正的posix命名管道,由mkfifo(或python脚本中的'os.mkfifo()')制作的 –

回答

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) 
+0

那么,在这种情况下使用read_line()会更有效率,但我猜这里没有解决方案对于任何大小的二进制文件使用所有的char-codes而不使用另一个fifo来制作控件 感谢任何方式 –

相关问题