20

我创建了一个 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

有谁知道怎么了?

4

2 回答 2

17

根据手册页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.

于 2013-01-15T20:02:42.250 回答
-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')
于 2013-01-15T20:07:31.893 回答