gpt4 book ai didi

python - 检测命名管道的关闭

转载 作者:太空宇宙 更新时间:2023-11-04 00:04:38 25 4
gpt4 key购买 nike

我有一个将数据写入命名管道的 C 程序和一个从命名管道读取数据的 Python 程序,如下所示:

p = open('/path/to/named/pipe', 'r')
...
data = p.read(size)

当 C 程序退出时,它会关闭管道。

如何从 Python 端检测到这一点?我已经尝试为 SIGPIPE 安装一个处理程序,但似乎 SIGPIPE 只在尝试写入关闭的管道时发生,而不是从中读取。由于另一端的 EOF,我还预计 p.read(size) 可能会返回一个长度为零的字符串,但实际上它只是挂起等待数据。

如何检测并处理这种情况?

最佳答案

您可以使用 the select module监视管道的状态。在 Linux 上(select.poll() 可用,以下代码将检测是否存在关闭的管道:

import select

# ...

poller = select.poll()
# Register the "hangup" event on p
poller.register(p, select.POLLHUP)

# Call poller.poll with 0s as timeout
for descriptor, mask in poller.poll(0):
# Can contain at most one element, but still:
if descriptor == p.fileno() and mask & select.POLLHUP:
print('The pipe is closed on the other end.')
p.close()

其他操作系统也存在可以检测此类情况的类似方法。

之所以在调用read时挂起,是因为IO阻塞了。您可以使用 os.set_blocking 将其变为非阻塞(并让 read 返回一个空字符串) ,但这仍然不允许您检测另一端的管道何时关闭。

关于python - 检测命名管道的关闭,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29404407/

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