Getting readline to block on a FIFO

孤街醉人 提交于 2019-12-07 01:02:26

问题


I create a fifo:

mkfifo tofetch

I run this python code:

fetchlistfile = file("tofetch", "r")
while 1:
    nextfetch = fetchlistfile.readline()
    print nextfetch

It stalls on readline, as I would hope. I run:

echo "test" > tofetch

And my program doesn't stall anymore. It reads the line, and then continues looping forever. Why won't it stall again when there's no new data?

I also tried looking on "not fetchlistfile.closed", I wouldn't mind reopening it after every write, but Python thinks the fifo is still open.


回答1:


According to the documentation for readline, it returns the empty string if and only if you're at end-of-file. Closed isn't the same as end-of-file. The file object will only be closed when you call .close(). When your code reaches the end of the file, readline() keeps returning the empty string.

If you just use the file object as an iterator, Python will automatically read a line at a time and stop at end-of-file. Like this:

fetchlistfile = file("tofetch", "r")
for nextfetch in fetchlistfile:
    print nextfetch

The echo "test" > tofetch command opens the named pipe, writes "test" to it, and closes it's end of the pipe. Because the writing end of the pipe is closed, the reading end sees end-of-file.



来源:https://stackoverflow.com/questions/2406365/getting-readline-to-block-on-a-fifo

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!