如何无阻塞地读取已命名的FIFO? [英] How to read named FIFO non-blockingly?
本文介绍了如何无阻塞地读取已命名的FIFO?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我创建一个FIFO,并从a.py中以只读且非阻塞的方式定期打开它:
I create a FIFO, and periodically open it in read-only and non-blockingly mode from 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:
From b.py, open the fifo for writing:
out = open(fifo, 'w')
out.write('sth')
然后a.py将引发错误:
Then a.py will raise an error:
buffer = os.read(io, BUFFER_SIZE)
OSError: [Errno 11] Resource temporarily unavailable
有人知道怎么了吗?
推荐答案
根据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.
所以您得到的是没有可供读取的数据.这样处理错误是安全的:
So what you're getting is that there is no data available for reading. It is safe to handle the error like this:
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
.
Make sure you have the errno module imported: import errno
.
这篇关于如何无阻塞地读取已命名的FIFO?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文