Can I open a named pipe on Linux for non-blocked writing in Python?

送分小仙女□ 提交于 2019-12-10 03:32:32

问题


I created a fifo file using mkfifo. Is it possible to open/write to this without blocking? I'd like to be agnostic whether there is a reader or not.

The following:

with open('fifo', 'wb', 0) as file:
    file.write(b'howdy')

Just stalls at the open until I do a cat fifo from another shell. I want my program to make progress regardless there's a data consumer watching or not.

Is there a different linux mechanism I should be using perhaps?


回答1:


From man 7 fifo:

A process can open a FIFO in nonblocking mode. In this case, opening or read-only will succeed even if no-one has opened on the write side yet, opening for write-only will fail with ENXIO (no such device or address) unless the other end has already been opened.

So the first solution is opening FIFO with O_NONBLOCK. In this case you can check errno: if it is equal to ENXIO, then you can try opening FIFO later.

import errno
import posix

try:
    posix.open('fifo', posix.O_WRONLY | posix.O_NONBLOCK)
except OSError as ex:
    if ex.errno == errno.ENXIO:
        pass # try later

The other possible way is opening FIFO with O_RDWR flag. It will not block in this case. Other process can open it with O_RDONLY without problem.

import posix
posix.open('fifo', posix.O_RDWR)


来源:https://stackoverflow.com/questions/34754397/can-i-open-a-named-pipe-on-linux-for-non-blocked-writing-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!