asullaherc asullaherc - 2 months ago 16x
Ruby Question

Process.detach cause sinatra-1.4.7 auto exit

here is my code:

class App < Sinatra::Base
get "/" do
pid =fork do


when i
curl localhost:4567
, the server auto exit and the output is: - - [13/Aug/2016:23:45:18 CST] "GET / HTTP/1.1" 200 0
- -> /
[2016-08-13 23:45:18] INFO WEBrick::HTTPServer#start done.
== Sinatra has ended his set (crowd applauds)

my environment is:

Linux Mint 17.3 Rosa
ruby 2.3.1p112 (2016-04-26 revision 54768) [x86_64-linux]


It's not Process.detach that causes Sinatra to quit, but the fact that the forked process ends and runs its at_exit hooks, which shut down the server (though I'm not quite sure how that can leak from the child process to the parent).

There's a couple of simple ways to prevent this.

  1. I prefer this set-and-forget solution:

    configure do
      disable :traps

    The downside is that Ctrl-C causes a not-so-graceful exit.

  2. Alternatively, add this to the beginning of any fork block:

    settings.running_server = nil

    The downside is that you need to remember to add this to all forked code.

You might also find someone suggesting at_exit { Process.exit! } in all fork blocks, but I think it's less reliable because other at_exit handlers could interfere with it.

Unfortunately, I don't see any configuration option in Sinatra that would fix forking and still allow graceful handling of Ctrl-C.