public
Created

  • Download Gist
a.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33
# $ 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

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.