Hi,

I'm writing a multi-threaded server, and would like to stop it on a
signal (SIGINT on Ctrl-C in this case).
The problem is that after the first connection is accepted, and then
Ctrl-C is hit, the "while accept" loop doesn't break. If you hit Ctrl-
C before any connections, it just works fine. And the single-threaded
version, of course, works
as well.

Could somebody explain what am I doing wrong?

Below is a simple application that reproduces the problem. Change the
last line to "server.serve_seq" to run a single-threaded version.

Thanks in advance!


#!/usr/local/bin/ruby -w

require 'socket'

class MyServer
  def initialize
    @servsock = TCPServer.new("127.0.0.1", 1111)
  end

  def work(sock)
    begin
      lines = 0
      lines += 1 while sock.gets
      puts "Got #{lines} lines."
    rescue Exception => e
      print "exception: "; p e
    ensure
      sock.close
    end
  end

  def serve_mt
    while clisock = @servsock.accept
      Thread.new(clisock) { |sock| work(sock) }
    end
  end

  def serve_seq
    while sock = @servsock.accept
      work(sock)
    end
  end

  def shutdown
    return nil if @servsock.nil? or @servsock.closed?
    puts "Shutting down..."
    @servsock.close
  end
end

server = MyServer.new
Signal.trap("INT") { server.shutdown }
server.serve_mt