Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 如何处理Sinatra的陷阱_Ruby_Sinatra - Fatal编程技术网

Ruby 如何处理Sinatra的陷阱

Ruby 如何处理Sinatra的陷阱,ruby,sinatra,Ruby,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,它应该等待线程完成。在应用程序关闭之前,您可以使用运行代码

我想捕获陷阱,需要在退出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,它应该等待线程完成。

在应用程序关闭之前,您可以使用运行代码

如果您需要在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  

那么什么不起作用呢?如果我按Ctrl+C,它会立即终止,这就是sinatra通常的工作方式,我需要为我的sinatra应用程序使用自定义陷阱。而不是捕获陷阱,你试过了吗?我无法将thread.join与at_exit一起使用,因为变量没有被传输到at_exit函数未定义的方法'join',用于nil:NilClass NoMethodError-我在get/test调用之后立即进行测试,这是因为at_exit不会继承Sinatra应用程序的实例变量。尝试在at_exit函数之前设置thread=nil,然后说thread=thread.new{…}而不是headrequire'sinatra'必须在定义at_exitinteresisting之后,确定。