Salt
Salt

Reputation: 167

How do I listen to STDIN input without pausing my script?

I have a while loop consistently listening to incoming connections and outputting them to console. I would like to be able to issue commands via the console without affecting the output. I've tried:

Thread.new do
    while true
        input   = gets.chomp
        puts "So I herd u sed, \"#{input}\"."
        #Commands would be in this scope
    end
end

However, that seems to pause my entire script until input is received; and even then, some threads I have initiated before this one don't seem to execute. I've tried looking at TCPSocket's select() method to no avail.

Upvotes: 4

Views: 3282

Answers (2)

Mladen Jablanović
Mladen Jablanović

Reputation: 44080

Not sure where are the commands you want to "continue running" in your example. Try this small script:

Thread.new do
  loop do
    s = gets.chomp
    puts "You entered #{s}"
    exit if s == 'end'
  end
end

i = 0
loop do
  puts "And the script is still running (#{i})..."
  i += 1
  sleep 1
end

Reading from STDIN is done in a separate thread, while the main script continues to work.

Upvotes: 6

tokland
tokland

Reputation: 67880

Ruby uses green threads, so blocking system calls will block all threads anyway. An idea:

require 'io/wait'

while true
  if $stdin.ready?
    line = $stdin.readline.strip
    p "line from stdin: #{line}"
  end
  p "really, I am working here"
  sleep 0.1
end

Upvotes: 2

Related Questions