Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 715
Travis Griggs Avatar asked Jan 12 '16 21:01

Travis Griggs


1 Answers

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)
like image 54
Oleg Andriyanov Avatar answered Sep 18 '22 12:09

Oleg Andriyanov