为什么只读打开一个命名pipe道块?

在使用Python处理各种UNIX(Linux,FreeBSD和MacOS X)命名pipe道(FIFOs)时,我注意到了一些奇怪的地方。 第一个,也许是最烦人的是试图打开一个空/空闲的FIFO只读将阻塞(除非我使用os.O_NONBLOCKos.open()调用较低级别)。 但是,如果我打开它的读/写,那么我没有阻止。

例子:

 f = open('./myfifo', 'r') # Blocks unless data is already in the pipe f = os.open('./myfifo', os.O_RDONLY) # ditto # Contrast to: f = open('./myfifo', 'w+') # does NOT block f = os.open('./myfifo', os.O_RDWR) # ditto f = os.open('./myfifo', os.O_RDONLY|os.O_NONBLOCK) # ditto 

我只是好奇,为什么。 为什么打开的调用块,而不是一些后续的读取操作?

另外我注意到一个非阻塞文件描述符可以在Python中performance出不同的行为。 在os.open()os.O_NONBLOCK用于初始打开操作的情况下,如果文件描述符中的数据没有准备好, os.read()似乎会返回一个空string。 但是,如果我使用fcntl.fcnt(f.fileno(), fcntl.F_SETFL, fcntl.GETFL | os.O_NONBLOCK)os.read引发exception( errno.EWOULDBLOCK

是否有一些其他的标志是由正常的open()不是由我的os.open()例子设置? 他们有什么不同,为什么?

这只是它被定义的方式。 从open()函数的Open Group页面

 O_NONBLOCK When opening a FIFO with O_RDONLY or O_WRONLY set: If O_NONBLOCK is set: An open() for reading only will return without delay. An open() for writing only will return an error if no process currently has the file open for reading. If O_NONBLOCK is clear: An open() for reading only will block the calling thread until a thread opens the file for writing. An open() for writing only will block the calling thread until a thread opens the file for reading.