我可以在Linux上打开命名管道以使用Python进行非阻塞写入吗? [英] Can I open a named pipe on Linux for non-blocked writing in Python?

查看:174
本文介绍了我可以在Linux上打开命名管道以使用Python进行非阻塞写入吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用mkfifo创建了一个fifo文件.是否可以在不阻塞的情况下打开/写入?我想知道是否有读者.

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.

以下内容:

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

只是停在开放位置,直到我从另一个外壳执行cat fifo为止.我希望我的程序能够取得进展,无论是否有数据消费者在关注.

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.

也许我应该使用一种不同的linux机制吗?

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

推荐答案

来自man 7 fifo:

一个进程可以在非阻塞模式下打开FIFO.在这种情况下,即使未在写侧打开任何人,打开或只读操作也将成功,除非ENXIO(没有此类设备或地址)打开,否则写操作的打开操作将失败,除非另一端已被打开.

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.

因此,第一个解决方案是使用O_NONBLOCK打开FIFO.在这种情况下,您可以检查errno:如果它等于ENXIO,则可以稍后尝试打开FIFO.

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

另一种可能的方法是使用O_RDWR标志打开FIFO.在这种情况下,它不会阻塞.其他进程可以使用O_RDONLY毫无问题地打开它.

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)

这篇关于我可以在Linux上打开命名管道以使用Python进行非阻塞写入吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆