2015-09-16 98 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來製作控件 感謝任何方式 –

相關問題