Kill all threads for completion
I am trying to create an application in ruby ββthat can be run from the command line and it does two functions: it does continuous work ( loop
with sleep
that starts some action [parsing a remote pipe]) with one thread and sinatra on the second thread. My code (simplified) looks like this:
require 'sinatra'
class MyApp < Sinatra::Base
get '/' do
"Hello!"
end
end
threads = []
threads << Thread.new do
loop do
# do something heavy
sleep 10
end
end
threads << Thread.new do
MyApp.run!
end
threads.each { |t| t.join }
The above code works really well - the synatra application starts available under 4567 ports, and the task do something heavy
starts every 10 seconds. However, I cannot kill this script.
I run it with ruby app.rb
but killing it with ctrl + c doesn't work. It only kills the sinatra stream, but the second one still works and in order to stop the script I need to close the terminal window.
I tried to kill all threads in SIGNINT but also didn't work as expected
trap "SIGINT" do
puts "Exiting"
threads.each { |t| Thread.kill t }
exit 130
end
Can you help me? Thanks in advance.
source to share
To catch ctrl-c change "SIGINT" to "INT".
trap("INT") {
puts "trapping"
threads.each{|t|
puts "killing"
Thread.kill t
}
}
To configure Sinatra to skip trap hooks:
class MyApp < Sinatra::Base
configure do
set :traps, false
end
...
Ref: Ruby Signals Module
To display the available Ruby signals: Signal.list.keys
Link: Sinatra Intro
(When I run your code and the INT hook, I get the Sinatra socket warning "Already in use." I suppose this is good for your purposes, or you can solve this by doing a graceful Sinatra shutdown. See Sinatra - Server Shutdown On Demand )
source to share