如何将用户中断添加到无限循环中?
我有一个 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 Kernel.trap 为 Ctrl-C 安装信号处理程序:
Use Kernel.trap to install a signal handler for Ctrl-C:
我认为您必须在单独的线程中检查退出条件:
顺便说一句,您必须输入
q
才能退出,因为这就是标准输入的工作原理。I think you will have to check the exit condition in a separate thread:
BTW, you will have to enter
q<Enter>
to exit, as that's how standard input works.