Gracefully exiting from thread in Ruby

Posted by jasonbogd on Stack Overflow See other posts from Stack Overflow or by jasonbogd
Published on 2010-03-21T02:03:49Z Indexed on 2010/03/21 2:11 UTC
Read the original article Hit count: 463

Hi,

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.

© Stack Overflow or respective owner

Related posts about ruby

Related posts about ruby-on-rails