[英]Detect close of named pipe
我有一个将数据写入命名管道的C程序和一个从命名管道读取数据的Python程序,如下所示:
p = open('/path/to/named/pipe', 'r')
...
data = p.read(size)
C程序退出时,它将关闭管道。
如何从Python端检测到这一点? 我曾尝试为SIGPIPE安装处理程序,但似乎SIGPIPE仅在尝试写入封闭的管道而不是从封闭管道读取时发生。 我还期望p.read(size)
可能由于另一端的EOF而返回长度为零的字符串,但实际上它只是挂起以等待数据。
我如何发现这种情况并进行处理?
您可以使用select
模块来监视管道的状态。 在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()
对于其他OS,也存在可以检测到这种情况的类似方法。
调用read
时挂起的原因是IO正在阻塞。 您可以使用os.set_blocking
将其变为非阻塞(并已read
返回一个空字符串),但这仍然不允许您检测另一端的管道何时关闭。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.