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

发布于 2024-10-08 15:44:40 字数 234 浏览 7 评论 0原文

我有一个 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

在每次迭代中,不应询问用户输入。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

金兰素衣 2024-10-15 15:44:40

使用 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"

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"
樱花细雨 2024-10-15 15:44:40

我认为您必须在单独的线程中检查退出条件:

# 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

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文