cha*_*nin 18 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)
Run Code Online (Sandbox Code Playgroud)
从b.py,打开fifo进行写作:
out = open(fifo, 'w')
out.write('sth')
Run Code Online (Sandbox Code Playgroud)
然后a.py将引发错误:
buffer = os.read(io, BUFFER_SIZE)
OSError: [Errno 11] Resource temporarily unavailable
Run Code Online (Sandbox Code Playgroud)
谁知道什么是错的?
Jon*_*fer 15
根据以下手册read(2):
Run Code Online (Sandbox Code Playgroud)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
Run Code Online (Sandbox Code Playgroud)
确保已导入errno模块:import errno.