为什么只读打开的命名管道会阻塞? [英] Why does a read-only open of a named pipe block?

查看:58
本文介绍了为什么只读打开的命名管道会阻塞?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在使用 Python 处理各种 UNIX(Linux、FreeBSD 和 MacOS X)下的命名管道 (FIFO) 时,我注意到了一些奇怪之处.第一个,也许是最烦人的是,尝试以只读方式打开空/空闲 FIFO 会阻塞(除非我使用 os.O_NONBLOCK 和较低级别的 os.open()代码>调用).但是,如果我打开它进行读/写,则不会出现阻塞.

I've noticed a couple of oddities when dealing with named pipes (FIFOs) under various flavors of UNIX (Linux, FreeBSD and MacOS X) using Python. The first, and perhaps most annoying is that attempts to open an empty/idle FIFO read-only will block (unless I use os.O_NONBLOCK with the lower level os.open() call). However, if I open it for read/write then I get no blocking.

示例:

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

我只是好奇为什么.为什么open调用会阻塞而不是一些后续的读操作?

I'm just curious why. Why does the open call block rather than some subsequent read operation?

我还注意到非阻塞文件描述符可以在 Python 中表现出不同的行为.在我使用 os.open()os.O_NONBLOCK 进行初始打开操作的情况下,os.read() 似乎如果文件描述符上的数据未准备好,则返回空字符串.但是,如果我使用 fcntl.fcnt(f.fileno(), fcntl.F_SETFL, fcntl.GETFL | os.O_NONBLOCK) 那么 os.read 会引发异常(errno.EWOULDBLOCK)

Also I've noticed that a non-blocking file descriptor can exhibit to different behaviors in Python. In the case where I use os.open() with the os.O_NONBLOCK for the initial opening operation then an os.read() seems to return an empty string if data isn't ready on the file descriptor. However, if I use fcntl.fcnt(f.fileno(), fcntl.F_SETFL, fcntl.GETFL | os.O_NONBLOCK) then an os.read raises an exception (errno.EWOULDBLOCK)

我的 os.open() 示例中未设置的其他标志是否由普通 open() 设置?它们有何不同以及为什么不同?

Is there some other flag being set by the normal open() that's not set by my os.open() example? How are they different and why?

推荐答案

这就是它的定义方式.来自 open()函数

That's just the way it's defined. From the Open Group page for the open() function

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.

这篇关于为什么只读打开的命名管道会阻塞?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆