On Wed, 1 Nov 2006, Tom Pollard wrote:
>
> On Oct 31, 2006, at 6:23 PM, wrote:
>> On Wed, 1 Nov 2006 wrote:
>>> How can I perform a nonblocking IO read? That is, read whatever is there
>>> to read and return. If there's nothing yet, just return.
>
> That's what the Unix read() function does ("man 2 read"), available in Ruby
> as IO#sysread(). The ri documentation doesn't explain much about how to use
> Ruby's sysread, unfortunately.
no, that blocks. try this:
harp:~ > ruby -e 'STDIN.sysread(1)'
it blocks. the OP wants a non-blocking call. eg
harp:~ > ruby -r io/nonblock -e 'STDIN.nonblock{ STDIN.sysread(1) }'
-e:1:in `sysread': Resource temporarily unavailable (Errno::EAGAIN)
from -e:1
from /home/ahoward//lib/ruby/1.8/io/nonblock.rb:19:in `nonblock'
from -e:1
> The select() function (Kernel#select, in Ruby) is the standard way to do IO
> multiplexing under Unix. You give it a list of file handles on which you're
> waiting to be able to read or write, and it returns when one or more of them
> is ready. Windows provides a select() function, too, but it only supports
> sockets (not pipes or ordinary file IO.) The Win32 API generally doesn't
> provide non-blocking IO methods, because it's assumed you'll use threads if
> you want to do something else while waiting for IO.
right. but ruby's thread are green and, on windows, block the entire process
when waiting on IO so not an option here.
> Check other IO channels, wait for other sorts of events, do work - whatever.
> Where do come from asserting that the use of non-blocking IO represents a
> "design flaw"?
because nine times out of ten code has nothing to do if no input is available.
if it does that's another story, but then there are basically two options:
- use select or an event abstraction in one giant loop. if you do this you are
going to block anyhow, only based on all inputs, not just one.
- use threads, only you can't if you're wanting ruby code to run nb in windows.
i'm not saying there is never a case for nbio - i use it myself - just that,
unless a developer has a good reason to be doing something else it's not
required and, as a search of ruby-talk will show, that is often the case.
regards.
-a
--
my religion is very simple. my religion is kindness. -- the dalai lama