gpt4 book ai didi

python - 如何非阻塞地读取命名的 FIFO?

转载 作者:IT老高 更新时间:2023-10-28 21:04:12 27 4
gpt4 key购买 nike

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

有人知道怎么回事吗?

最佳答案

根据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

关于python - 如何非阻塞地读取命名的 FIFO?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14345816/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com