从
POSIX specification of the read system call(强调我的):
When attempting to read from an empty pipe or FIFO:
If no process has the pipe open for writing, read() shall return 0 to
indicate end-of-file.
If some process has the pipe open for writing and O_NONBLOCK is set,
read() shall return -1 and set errno to [EAGAIN].
所以基本上你的第二个假设是错误的:
If the writer has the pipe opened, but no data is in the fifo, empty str (”) is also returned
这将违反规范,我无法在我的机器上重现这种行为(它为我提供了EAGAIN).这不是一个大问题,但是您可以捕获异常并重试:
import errno
def safe_read(fd, size=1024):
”’ reads data from a pipe and returns `None` on EAGAIN ”’
try:
return os.read(fd, size)
except OSError, exc:
if exc.errno == errno.EAGAIN:
return None
raise