[英]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.