在典型的UNIX方式中,read(2)返回0字节以指示文件结尾,这可能意味着:文件中没有更多字节
套接字的另一端已关闭连接
作者已关闭了一个管道
在您的例子中,fifo.read()返回一个空字符串,因为编写器已关闭其文件描述符。
你应该发现这种情况并跳出你的圈子:
读卡器.py:import os
import errno
FIFO = 'mypipe'
try:
os.mkfifo(FIFO)
except OSError as oe:
if oe.errno != errno.EEXIST:
raise
print("Opening FIFO...")
with open(FIFO) as fifo:
print("FIFO opened")
while True:
data = fifo.read()
if len(data) == 0:
print("Writer closed")
break
print('Read: "{0}"'.format(data))
示例会话
终端1:$ python reader.py
Opening FIFO...
终端2:$ echo -n 'hello' > mypipe
终端1:FIFO opened
Read: "hello"
Writer closed
$
更新1-持续重新打开
您表示希望继续监听管道上的写入,甚至可能在写入程序关闭之后。
为了有效地做到这一点,你可以(而且应该)利用以下事实Normally, opening the FIFO blocks until the other end is opened also.
在这里,我在open和read循环周围添加另一个循环。这样,一旦管道关闭,代码将尝试重新打开它,这将阻塞直到另一个编写器打开管道:import os
import errno
FIFO = 'mypipe'
try:
os.mkfifo(FIFO)
except OSError as oe:
if oe.errno != errno.EEXIST:
raise
while True:
print("Opening FIFO...")
with open(FIFO) as fifo:
print("FIFO opened")
while True:
data = fifo.read()
if len(data) == 0:
print("Writer closed")
break
print('Read: "{0}"'.format(data))
终端1:$ python reader.py
Opening FIFO...
终端2:$ echo -n 'hello' > mypipe
终端1:FIFO opened
Read: "hello"
Writer closed
Opening FIFO...
终端2:$ echo -n 'hello' > mypipe
终端1:FIFO opened
Read: "hello"
Writer closed
Opening FIFO...
。。。等等。
您可以通过阅读管道的man页了解更多信息: