在 Ruby 中优雅地退出线程
我正在尝试 Mongrel 并使用以下代码:
require 'rubygems'
require 'mongrel'
class SimpleHandler < Mongrel::HttpHandler
def process(request, response)
response.start(200) do |head, out|
head["Content-Type"] = "text/plain"
out.write("Hello World!\n")
end
end
end
h = Mongrel::HttpServer.new("0.0.0.0", "3000")
h.register("/test", SimpleHandler.new)
puts "Press Control-C to exit"
h.run.join
trap("INT") do
puts "Exiting..."
end
基本上,这只是打印出“Hello World!”当我转到 localhost:3000/test 时。它工作得很好,我可以用 Control-C 关闭程序。但是当我按 Control-C 时,会输出以下内容:
my_web_server.rb:17:in `join': Interrupt
from my_web_server.rb:17
因此,我尝试将 trap("INT")
语句放在末尾,但它没有被调用。解决方案?
谢谢。
I am trying out Mongrel and using the following code:
require 'rubygems'
require 'mongrel'
class SimpleHandler < Mongrel::HttpHandler
def process(request, response)
response.start(200) do |head, out|
head["Content-Type"] = "text/plain"
out.write("Hello World!\n")
end
end
end
h = Mongrel::HttpServer.new("0.0.0.0", "3000")
h.register("/test", SimpleHandler.new)
puts "Press Control-C to exit"
h.run.join
trap("INT") do
puts "Exiting..."
end
Basically, this just prints out "Hello World!" when I go to localhost:3000/test. It works fine, and I can close the program with Control-C. But when I press Control-C, this gets outputted:
my_web_server.rb:17:in `join': Interrupt
from my_web_server.rb:17
So I tried putting that trap("INT")
statement at the end, but it isn't getting called. Solution?
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您只想在没有堆栈跟踪的情况下退出,则无需捕获 INT。 control-c 会导致“中断”异常。因此,为了让你的程序在 control-C 上退出而不出现难看的堆栈跟踪,请捕获该异常:
There's no need to trap INT if all you want to do is exit without the stack trace. A control-c causes an "Interrupt" exception. So to let your program exit on control-C without the ugly stack trace, catch that exception: