检测阅读器何时关闭命名管道(FIFO) [英] Detect when reader closes named pipe (FIFO)

查看:115
本文介绍了检测阅读器何时关闭命名管道(FIFO)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

作者是否有办法知道读者已经关闭了命名管道的末端(或退出了),而没有写出 呢?

Is there any way for a writer to know that a reader has closed its end of a named pipe (or exited), without writing to it?

我需要知道这一点,因为我写入管道的初始数据是不同的.读者希望在其余数据到来之前有一个初始标头.

I need to know this because the initial data I write to the pipe is different; the reader is expecting an initial header before the rest of the data comes.

当前,当我的write()失败并显示EPIPE时,我会检测到此错误.然后,我设置一个标志,上面写着下次,发送标题".但是,在我写任何东西之前,读者有可能关闭并重新打开管道.在这种情况下,我永远不会意识到他的工作,也不会发送他期望的标题.

Currently, I detect this when my write() fails with EPIPE. I then set a flag that says "next time, send the header". However, it is possible for the reader to close and re-open the pipe before I've written anything. In this case, I never realize what he's done, and don't send the header he is expecting.

是否有某种异步事件类型的东西可能会对您有所帮助?我没有看到任何正在发送的信号.

Is there any sort of async event type thing that might help here? I'm not seeing any signals being sent.

请注意,我没有包含任何语言标签,因为该问题应视为与语言无关.我的代码是Python,但是答案应该适用于C或具有系统调用级绑定的任何其他语言.

推荐答案

奇怪的是,当最后一个读取器关闭管道时,select表示该管道可读:

Oddly enough, it appears that when the last reader closes the pipe, select indicates that the pipe is readable:

writer.py

#!/usr/bin/env python
import os
import select
import time

NAME = 'fifo2'

os.mkfifo(NAME)


def select_test(fd, r=True, w=True, x=True):
    rset = [fd] if r else []
    wset = [fd] if w else []
    xset = [fd] if x else []

    t0 = time.time()
    r,w,x = select.select(rset, wset, xset)

    print 'After {0} sec:'.format(time.time() - t0)
    if fd in r: print ' {0} is readable'.format(fd)
    if fd in w: print ' {0} is writable'.format(fd)
    if fd in x: print ' {0} is exceptional'.format(fd)

try:
    fd = os.open(NAME, os.O_WRONLY)
    print '{0} opened for writing'.format(NAME)

    print 'select 1'
    select_test(fd)

    os.write(fd, 'test')
    print 'wrote data'

    print 'select 2'
    select_test(fd)

    print 'select 3 (no write)'
    select_test(fd, w=False)

finally:
    os.unlink(NAME)

演示:

端子1:

$ ./pipe_example_simple.py
fifo2 opened for writing
select 1
After 1.59740447998e-05 sec:
 3 is writable
wrote data
select 2
After 2.86102294922e-06 sec:
 3 is writable
select 3 (no write)
After 2.15910816193 sec:
 3 is readable

端子2:

$ cat fifo2
test
# (wait a sec, then Ctrl+C)

这篇关于检测阅读器何时关闭命名管道(FIFO)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆