如何将用户中断添加到无限循环?

时间:2022-05-26 07:48:29

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'?

我有一个ruby脚本,从下面无限打印数字从1开始。如何通过终端中的“Ctrl + C”或“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.

通过每次迭代,都不应该询问用户输入。

2 个解决方案

#1


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.

顺便说一句,您必须输入q 才能退出,因为这是标准输入的工作方式。

#2


13  

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

使用Kernel.trap为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"

#1


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.

顺便说一句,您必须输入q 才能退出,因为这是标准输入的工作方式。

#2


13  

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

使用Kernel.trap为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"