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?
From man 7 fifo
:
A process can open a FIFO in nonblocking mode. In this case, opening for 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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With