为什么我不能终止 Sinatra 服务器?

Why can't I terminate Sinatra server?

为什么我不能使用以下命令停止 Sinatra 服务器:

post '/terminate' do
  Thread.current.kill
end

我在浏览器中输入:

localhost:<port>/terminate

但它从不终止服务器,Sinatra 说它不知道这样的路径。可能是什么原因?

浏览器将执行 "GET" http 请求。

如果你改成

get '/terminate' do
  exit # system exit!
end

我认为它会起作用。

adzdavies 是部分正确的,你没有点击路由,因为你的浏览器正在发出一个 GET 请求并且你已经定义了一个 post 路由,但是 exit 不会'也不起作用,它只会向你吐出一个错误。引发 Interrupt 异常也是如此。 Thread.current.kill只是结束当前线程的执行,好像是杀掉当前实例和服务器will just spawn a new instance on the next request,不会杀掉服务器,服务器有自己的进程。

require 'sinatra/base'

class SillyWaysToKillTheServer < Sinatra::Base

  enable :inline_templates

  get "/" do
    erb :index
  end

  get '/terminate' do
    exit # system exit!
  end

  get "/threadkill" do
    Thread.current.kill
  end

  get "/exception" do
    raise Interrupt, "Kill the server, please!"
  end

  run! if __FILE__ == [=10=]
end

__END__

@@ layout
<html>
<body>
  <%= yield %>
</body>
</html>

@@ index

<p><a href="/terminate">terminate</a></p>
<p><a href="/threadkill">threadkill</a></p>
<p><a href="/exception">exception</a></p>

Sinatra 是一个框架,而不是服务器。服务器有自己的进程和 运行 一个启动新线程或分叉的小循环(Thin 使用线程作为其模型,例如 Unicorn 使用预分叉)或任何 运行 您拥有的 Sinatra 代码假如。要停止 服务器 ,要么使用 Ctrl+c 中断它,要么找到进程号并使用 kill 或像其他人一样通过 发送 SIGHUP确实。像这样停止网络服务器可能有一些很好的理由,但我想不出一个,也许不同的服务器会对线程终止和退出等做出不同的响应,但它们仍然不会停止你的服务器。

顺其自然。