首页 > 解决方案 > 如何处理 Sinatra 中的陷阱

问题描述

我想捕获陷阱并且需要在退出我的 Sinatra 应用程序之前执行自定义代码。在退出 Sinatra 之前,我需要等到我的线程执行完成。

require 'sinatra'

trap('INT') do
 puts "Trapped"
 @th.join
 exit(99)
end

get "/test" do
 "Hello World!"
 @th = Thread.new {sleep 30}
 puts @th
end  

如果我按Ctrl+C它应该等到线程完成。

标签: rubysinatra

解决方案


您可以at_exit在应用关闭之前运行代码。

如果您需要使用at_exit直到运行时才有的变量,您可以尝试将它们设为全局变量。例如,

thread = nil

at_exit do
  puts "Trapped"
  thread.join if thread
  exit(99)
end

require 'sinatra'
get "/test" do
  "Hello World!"
  thread = Thread.new {sleep 30}
  puts thread
end  

推荐阅读