python 管道 非阻塞_我可以在Linux上打开命名管道以使用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?

解决方案

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值