开发者

Why does a read-only open of a named pipe block?

开发者 https://www.devze.com 2023-03-01 02:56 出处:网络
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 t

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.

Examples:

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+')                           # doe开发者_JAVA百科s NOT block
f = os.open('./myfifo', os.O_RDWR)                   # ditto
f = os.open('./myfifo', os.O_RDONLY|os.O_NONBLOCK)   # ditto

Note: The behavior is NOT Python specific. Example in Python to make it easier to replicate and understand for a broader audience).

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

Also I've noticed that a non-blocking file descriptor can exhibit two 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 is not 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)

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?


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.
0

精彩评论

暂无评论...
验证码 换一张
取 消