简体   繁体   English

优雅地从Ruby中的线程退出

[英]Gracefully exiting from thread in Ruby

I am trying out Mongrel and using the following code: 我正在尝试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

Basically, this just prints out "Hello World!" 基本上,这只是打印出“ Hello World!” when I go to localhost:3000/test. 当我转到localhost:3000 / test时。 It works fine, and I can close the program with Control-C. 它工作正常,我可以使用Control-C关闭该程序。 But when I press Control-C, this gets outputted: 但是,当我按Control-C时,将输出:

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. 因此,我尝试将trap("INT")语句放在末尾,但是没有被调用。 Solution? 解?

Thanks. 谢谢。

There's no need to trap INT if all you want to do is exit without the stack trace. 如果您要做的就是在没有堆栈跟踪的情况下退出,则无需捕获INT。 A control-c causes an "Interrupt" exception. 控件c导致“中断”异常。 So to let your program exit on control-C without the ugly stack trace, catch that exception: 因此,要让您的程序在control-C上退出而没有难看的堆栈跟踪,请捕获该异常:

begin
  ... # do stuff
rescue Interrupt
  puts "Exiting..."
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM