Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a simple method for checking whether a Ruby IO instance will block on read()?

I'm looking for a method in Ruby which is basically this:

io.ready_for_read?

I just want to check whether a given IO object (in my case, the result of a popen call) has output available, i.e. a follow up call io.read(1) will not block.

These are the two options I see, neither of which I like:

  1. io.read_nonblock - too thin an abstraction of Unix read() -- I don't want to deal with errno error handling.

  2. io.select with timeout 0 -- obfuscates the purpose of this simple operation.

Is there a better alternative that I have overlooked?

like image 997
Dhskjlkakdh Avatar asked May 31 '09 01:05

Dhskjlkakdh


2 Answers

A bit late, but if you require 'io/wait', you can use ready? to verify that the IO can be read without blocking. Granted, depending upon how much you intend on reading (and how you plan to do it) your IO object may still block, but this should help. I'm not sure if this library is supported on all platforms, and I also don't know why this functionality was separated from the rest of the IO library. See more here: http://ruby-doc.org/stdlib/libdoc/io/wait/rdoc/

like image 100
Ian Eccles Avatar answered Nov 07 '22 17:11

Ian Eccles


I'm ready to conclude that no, there is no simple method to do this. Per Peter Cooper's suggestion, here is IO#ready_for_read?:

class IO
  def ready_for_read?
    result = IO.select([self], nil, nil, 0)
    result && (result.first.first == self)
  end
end
like image 38
Dhskjlkakdh Avatar answered Nov 07 '22 15:11

Dhskjlkakdh