如何在Python中正确写入FIFO? [英] How do I properly write to FIFOs in Python?

查看:309
本文介绍了如何在Python中正确写入FIFO?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我在Python中打开FIFO(命名管道)进行写入时,发生了非常奇怪的事情.考虑一下当我尝试打开一个FIFO以便在交互式解释器中进行写操作时发生的情况:

Something very strange is happening when I open FIFOs (named pipes) in Python for writing. Consider what happens when I try to open a FIFO for writing in a interactive interpreter:

>>> fifo_write = open('fifo', 'w')

以上行将阻塞,直到我打开另一个解释器并键入以下内容:

The above line blocks until I open another interpreter and type the following:

>>> fifo_read = open('fifo', 'r')
>>> fifo.read()

我不明白为什么我必须等待打开管道进行读取,但是让我们跳过它.上面的代码将阻塞,直到有可用的数据为止.但是,假设我回到第一个解释器窗口并输入:

I don't understand why I had to wait for the pipe to be opened for reading, but lets skip that. The above code will block until there's data available as expected. However let's say I go back to the first interpreter window and type:

>>> fifo_write.write("some testing data\n")
>>> fifo_write.flush()

预期的行为是,在第二个解释器上,对read的调用将返回,并且我们将在屏幕上看到数据,除非这对我而言没有发生.如果我呼叫os.fsync,则会发生以下情况:

The expected behavior is that on the second interpreter the call to read will return and we will see the data on the screen, except that is not happening to me. If I call os.fsync the following happens:

>>> import os
>>> fifo_write.flush()
>>> os.fsync(fifo_write.fileno())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: [Errno 22] Invalid argument

fifo阅读器仍在等待.但是,如果我调用fifo_writer.close(),则数据将被刷新.如果我使用shell命令来输送管道:

And the fifo reader is still waiting. However, if I call fifo_writer.close() then the data is flushed. If I use a shell command to feed the pipe:

$ echo "some data" > fifo

然后阅读器输出为:

>>> fifo_read.read()
'some data\n'

有人经历过吗?如果是这样,是否有解决方法?我当前的操作系统是带有Linux 2.6.38的Ubuntu 11.04.

Has anyone experienced this? If so is there a workaround for it? My current OS is Ubuntu 11.04 with Linux 2.6.38.

推荐答案

read()直到到达EOF才返回.

read() doesn't return until it reaches EOF.

您可以尝试指定要读取的字节数,例如read(4).在写入足够的字节之前,它仍然会阻塞,因此生产者必须至少写入那么多字节,然后调用flush().

You can try specifying the number of bytes you want read, like read(4). This will still block until enough bytes have been written, so the producer must write at least that many bytes and then call flush().

这篇关于如何在Python中正确写入FIFO?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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