如何读取命名FIFO非阻塞?

时间:2013-01-15 19:59:07

标签: python nonblocking fifo

我创建了一个FIFO,并定期从a.py以只读和非阻塞模式打开它:

os.mkfifo(cs_cmd_fifo_file, 0777)
io = os.open(fifo, os.O_RDONLY | os.O_NONBLOCK)
buffer = os.read(io, BUFFER_SIZE)

从b.py,打开fifo写作:

out = open(fifo, 'w')
out.write('sth')

然后a.py会引发错误:

buffer = os.read(io, BUFFER_SIZE)

OSError: [Errno 11] Resource temporarily unavailable

任何人都知道什么是错的?

2 个答案:

答案 0 :(得分:15)

根据read(2)

的联机帮助页
   EAGAIN or EWOULDBLOCK
          The  file  descriptor  fd refers to a socket and has been marked
          nonblocking   (O_NONBLOCK),   and   the   read   would    block.
          POSIX.1-2001  allows  either error to be returned for this case,
          and does not require these constants to have the same value,  so
          a portable application should check for both possibilities.

所以你得到的是没有可供阅读的数据。像这样处理错误是安全的:

try:
    buffer = os.read(io, BUFFER_SIZE)
except OSError as err:
    if err.errno == errno.EAGAIN or err.errno == errno.EWOULDBLOCK:
        buffer = None
    else:
        raise  # something else has happened -- better reraise

if buffer is None: 
    # nothing was received -- do something else
else:
    # buffer contains some received data -- do something with it

确保已导入errno模块:import errno

答案 1 :(得分:-2)

out = open(fifo, 'w')

谁会为你关闭它? 用这个替换你的open + write:

with open(fifo, 'w') as fp:
    fp.write('sth')

<强> UPD: 好吧,不要只是做这个:

out = os.open(fifo, os.O_NONBLOCK | os.O_WRONLY)
os.write(out, 'tetet')