Forum: Ruby reading from fifo with no writers blocks the whole process

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Cf931b1ef3b541ff6afd948b36fe81e3?d=identicon&s=25 Tomasz Wrobel (fmwr)
on 2009-04-30 11:42
Hi,

in my program I'm creating a thread, in which I open a FIFO and read
data from it.

pipe_listener_thread = Thread.new(ARGV[0]) do |fifoname|
  while true   # loop to reopen fifo, when it ends because of no writers
    fi = File.open(fifoname, "r")
    while line = fi.gets
      puts "msg: #{line}"
    end
    fi.close
  end
end

Everything works fine, except that when the thread is waiting to open
the fifo, whole process - all threads seem to be blocked. Such thing
doesn't happen when waiting for data (inner loop) - where the thread
alone gets blocked.

Please tell, if there's something wrong with this behavior, or it should
work that way.

Regs,
Tomasz Wrobel
E0d864d9677f3c1482a20152b7cac0e2?d=identicon&s=25 Robert Klemme (Guest)
on 2009-04-30 19:41
(Received via mailing list)
On 30.04.2009 11:42, Tomasz Wrobel wrote:
>   end
> end
>
> Everything works fine, except that when the thread is waiting to open
> the fifo, whole process - all threads seem to be blocked. Such thing
> doesn't happen when waiting for data (inner loop) - where the thread
> alone gets blocked.

First of all you should change your code to use the block form of
File.open.  This avoids keeping the file descriptor open in case of
errors.

You can do even more, see
http://blog.rubybestpractices.com/posts/rklemme/00...

> Please tell, if there's something wrong with this behavior, or it should
> work that way.

I believe this is perfectly ok.  Since IO indicates eof if there is no
more data in the fifo, it makes sense to block on open as long as there
is nothing to read.  Otherwise your program would mindlessly be looping
and burning CPU.

I do wonder though why reading from a named fifo ever reaches eof.  You
would expect the reading to continue.  OTOH that way you will be aware
if a program terminates which writes to the fifo and can react on it
appropriately.

Kind regards

  robert
This topic is locked and can not be replied to.