Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

ruby

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.

like image 432
Salt Avatar asked Feb 26 '23 09:02

Salt


1 Answers

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.

like image 67
Mladen Jablanović Avatar answered Mar 07 '23 00:03

Mladen Jablanović