fifo-循环阅读 [英] fifo - reading in a loop

查看:152
本文介绍了fifo-循环阅读的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用 os.mkfifo 进行简单的交流程序之间.我在循环读取fifo时遇到问题.

I want to use os.mkfifo for simple communication between programs. I have a problem with reading from the fifo in a loop.

考虑这个玩具示例,在该示例中,我有一位读者和一位作家与fifo合作.我希望能够循环运行阅读器以读取进入fifo的所有内容.

Consider this toy example, where I have a reader and a writer working with the fifo. I want to be able to run the reader in a loop to read everything that enters the fifo.

# reader.py
import os
import atexit

FIFO = 'json.fifo'

@atexit.register
def cleanup():
    try:
        os.unlink(FIFO)
    except:
        pass

def main():
    os.mkfifo(FIFO)
    with open(FIFO) as fifo:
#        for line in fifo:              # closes after single reading
#        for line in fifo.readlines():  # closes after single reading
        while True:
            line = fifo.read()          # will return empty lines (non-blocking)
            print repr(line)

main()

作者:

# writer.py
import sys

FIFO = 'json.fifo'


def main():
    with open(FIFO, 'a') as fifo:
        fifo.write(sys.argv[1])

main()

如果我运行python reader.py和更高版本的python writer.py foo,将打印"foo",但fifo将关闭并且阅读器将退出(或在while循环内旋转).我希望读者能留在循环中,这样我就可以多次执行作家了.

If I run python reader.py and later python writer.py foo, "foo" will be printed but the fifo will be closed and the reader will exit (or spin inside the while loop). I want reader to stay in the loop, so I can execute the writer many times.

修改

我使用此代码段来解决此问题:

I use this snippet to handle the issue:

def read_fifo(filename):
    while True:
        with open(filename) as fifo:
            yield fifo.read()

但是也许有一些更整洁的方式来处理它,而不是重复打开文件...

but maybe there is some neater way to handle it, instead of repetitively opening the file...

相关

推荐答案

FIFO(在读取器端)的工作方式完全如此:可以读取FIFO,直到所有写入器都消失了.然后它将EOF信号发送给阅读器.

A FIFO works (on the reader side) exactly this way: it can be read from, until all writers are gone. Then it signals EOF to the reader.

如果您希望读者继续阅读,则必须再次打开并从那里阅读.因此,您的摘录就是正确的选择.

If you want the reader to continue reading, you'll have to open again and read from there. So your snippet is exactly the way to go.

如果您有多个编写器,则必须确保它们编写的每个数据部分都小于PIPE_BUF,以免混淆消息.

If you have mutliple writers, you'll have to ensure that each data portion written by them is smaller than PIPE_BUF on order not to mix up the messages.

这篇关于fifo-循环阅读的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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