gpt4 book ai didi

python - 我可以在 Linux 上打开命名管道以在 Python 中进行非阻塞写入吗?

转载 作者:IT王子 更新时间:2023-10-29 00:25:23 26 4
gpt4 key购买 nike

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

以下内容:

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)

关于python - 我可以在 Linux 上打开命名管道以在 Python 中进行非阻塞写入吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34754397/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com