8

I have a ruby script below which infinitely prints numbers from 1 onward. How can I make the script stop its infinite execution through an interrupt in the terminal like 'Ctrl+C' or key 'q'?

a = 0
while( a )
  puts a
  a += 1
  # the code should quit if an interrupt of a character is given
end

Through every iteration, no user input should be asked.

sawa
  • 165,429
  • 45
  • 277
  • 381
boddhisattva
  • 6,908
  • 11
  • 48
  • 72

2 Answers2

15

Use Kernel.trap to install a signal handler for Ctrl-C:

#!/usr/bin/ruby

exit_requested = false
Kernel.trap( "INT" ) { exit_requested = true }

while !exit_requested
  print "Still running...\n"
  sleep 1
end
print "Exit was requested by user\n"
4

I think you will have to check the exit condition in a separate thread:

# check for exit condition
Thread.new do
  loop do
    exit if gets.chomp == 'q'
  end
end

a = 0
loop do
  a += 1
  puts a
  sleep 1
end

BTW, you will have to enter q<Enter> to exit, as that's how standard input works.

Mladen Jablanović
  • 43,461
  • 10
  • 90
  • 113