开发者

how to stop sinatra from running?

If ruby myapp.rb starts sinatra previewing at localhost:4567, how can I programatically stop/halt/kill it? Termi开发者_JS百科nal command (other than Ctrl-C), or Rake tasks would be fine.

I need to incorporate this into a Rake task or terminal.


In myapp.rb, add this before sinatra starts:

puts "This is process #{Process.pid}"

When you want to kill it, do this in a shell:

kill <pid>

Where <pid> is the number outputted by myapp.rb. If you want to do it in ruby:

Process.kill 'TERM', <pid>

Both of these will let sinatra run it's exit routine. If you don't want to type in the pid every time, have myapp.rb open a file and put it's pid in it. Then when you want to stop it, read the file and use that. Example:

# myapp.rb:
File.open('myapp.pid', 'w') {|f| f.write Process.pid }

# shell:
kill `cat myapp.pid`

# ruby:
Process.kill 'TERM', File.read('myapp.pid')


In OS X, from the command line (Terminal.app, or DTerm) just enter:

$ killall ruby

every ruby process will stop. Sinatra too.

In Linux (and other UNIXes), you can:

$ ps aux | grep ruby
$ kill <ruby-process-id>


The simples way to do that:

kill #{Process.pid}


To do this in a simple repeatable way, there's a few methods.

  1. Record the PID as you start your Sinatra server, e.g.

    # Run the Sinatra server and send it to background (using &)
    ruby my_sinatra_server.rb &
    
    # Record the PID of the last background process (using $!)
    MY_SINATRA_SERVER_PID=$!
    
    # Now go ahead and do your stuff...
    
    # When finished, kill the sinatra server (from the same shell)
    kill $MY_SINATRA_SERVER_PID
    
  2. Instead of using an env variable ($MY_SINATRA_SERVER) you can use a temporary file e.g. my_sinatra_server.pid

    # Run the Sinatra server and send it to background (using &)
    ruby my_sinatra_server.rb &
    
    # Record the PID of the last background process (using $!)
    echo $! > my_sinatra_server.pid
    
    # Now go ahead and do your stuff...
    
    # When finished, kill the sinatra server (from the same shell)
    kill $(< my_sinatra_server.pid)
    
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜