我可以在 Linux 上打开命名管道以在 Python 中进行非阻塞写入吗?
Can I open a named pipe on Linux for non-blocked writing in Python?
我使用 mkfifo
创建了一个 fifo 文件。是否可以 open/write 不阻塞?我想不知道是否有 reader。
以下:
with open('fifo', 'wb', 0) as file:
file.write(b'howdy')
我只是在开场停顿,直到我从另一个 shell 做一个 cat fifo
。无论是否有数据消费者观看,我都希望我的程序能够取得进展。
我是否应该使用不同的 linux 机制?
来自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.
所以第一个解决方案是用O_NONBLOCK
打开FIFO。这种情况你可以检查errno
:如果等于ENXIO
,那么你可以稍后尝试打开FIFO。
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
另一种可能的方法是使用 O_RDWR
标志打开 FIFO。在这种情况下它不会阻塞。其他进程可以用 O_RDONLY
打开它没有问题。
import posix
posix.open('fifo', posix.O_RDWR)
我使用 mkfifo
创建了一个 fifo 文件。是否可以 open/write 不阻塞?我想不知道是否有 reader。
以下:
with open('fifo', 'wb', 0) as file:
file.write(b'howdy')
我只是在开场停顿,直到我从另一个 shell 做一个 cat fifo
。无论是否有数据消费者观看,我都希望我的程序能够取得进展。
我是否应该使用不同的 linux 机制?
来自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.
所以第一个解决方案是用O_NONBLOCK
打开FIFO。这种情况你可以检查errno
:如果等于ENXIO
,那么你可以稍后尝试打开FIFO。
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
另一种可能的方法是使用 O_RDWR
标志打开 FIFO。在这种情况下它不会阻塞。其他进程可以用 O_RDONLY
打开它没有问题。
import posix
posix.open('fifo', posix.O_RDWR)