Poll STDIN for waiting input on Win32

B

Bill Atkins

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 =3D select [$stdin], [], [], 1
=20
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".

--=20
Bill Atkins
 
B

Bill Kelly

Hi,

From: "Bill Atkins said:
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... :)

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
 
D

Dale Martenson

---- Original message from Bill Kelly on 8/9/2005 10:25 AM:
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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,777
Messages
2,569,604
Members
45,214
Latest member
JFrancisDavis

Latest Threads

Top