Skip to content

Instantly share code, notes, and snippets.

@authorNari
Created November 28, 2012 01:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save authorNari/4158509 to your computer and use it in GitHub Desktop.
Save authorNari/4158509 to your computer and use it in GitHub Desktop.
# $ ruby a.rb
# $ nc localhost 8899
# $ pkill -TERM -f 'ruby this.rb'
require 'monitor'
require 'socket'
@monitor = Monitor.new
@threads = {}
Signal.trap("TERM") do
puts "trapped SIGTERM"
@monitor.synchronize do
puts "safe termination..."
@threads.values.each(&:join)
puts "...done"
exit
end
end
server = TCPServer.new(8899)
loop do
@monitor.synchronize do
th = Thread.new(server.accept) do |client|
client.puts "Hell"
sleep 20
client.puts "World..."
client.close
@threads.delete(Thread.current)
end
@threads[th] = th
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment