Poll STDIN for waiting input on Win32

How can I determine if there's input waiting on STDIN before calling
gets? This code doesn't do the trick:

···

----

while true
  r, w, e = select [$stdin], [], [], 1
  
  if r and r.include? $stdin
    puts "READY TO READ!"
  end
end

-----

Apparently, r always includes $stdin, so it just continuously prints
"READY TO READ".

--
Bill Atkins

Hi,

How can I determine if there's input waiting on STDIN before
calling gets?

<laugh> I just posted this a minute ago on the
Threading+TCPServer thread; if I'd seen your message
I'd have posted here instead... :slight_smile:

I use:

if WINDOWS_VERSION
  require 'dl'
  $win32_console_kbhit = Win32API.new("msvcrt", "_kbhit", , 'I')
  def console_input_ready?
    $win32_console_kbhit.call != 0
  end
else
  def console_input_ready?
    select([$stdin], nil, nil, 0) != nil
  end
end

Note that if you do a gets() when console_input_ready?
is true, you'll still block until the user hits <enter>.

BTW, I was using:

WINDOWS_VERSION = (RUBY_PLATFORM =~ /win32/) != nil

Regards,

Bill

···

From: "Bill Atkins" <batkins57@gmail.com>

---- Original message from Bill Kelly on 8/9/2005 10:25 AM:

From: "Bill Atkins" <batkins57@gmail.com>

How can I determine if there's input waiting on STDIN before
calling gets?
   

I use:

if WINDOWS_VERSION
require 'dl'
$win32_console_kbhit = Win32API.new("msvcrt", "_kbhit", , 'I')
def console_input_ready?
   $win32_console_kbhit.call != 0
end
else
def console_input_ready?
   select([$stdin], nil, nil, 0) != nil
end
end

Note that if you do a gets() when console_input_ready?
is true, you'll still block until the user hits <enter>.

BTW, I was using:

WINDOWS_VERSION = (RUBY_PLATFORM =~ /win32/) != nil

You can also define '_getch' to allow you to get the character right away and not have to wait for the user to press the <enter> key.

  require 'Win32API'

  $win32_console_kbhit = Win32API.new("msvcrt", "_kbhit", , 'I')
  $win32_console_cputs = Win32API.new("msvcrt", "_cputs", ['P'], 'I')
  $win32_console_getch = Win32API.new("msvcrt", "_getch", , 'I')

  def console_input_ready?
    $win32_console_kbhit.call != 0
  end

  def console_input
    $win32_console_getch.call
  end

  def console_output( str )
    $win32_console_cputs.call( str )
  end

  while true
    if console_input_ready? then
        ch = console_input
        print "ch: <#{ch.chr}>\n"
        break
    else
        console_output( "." )
        sleep 0.5
    end
  end