Search code examples
rubyprocesswebrick

how to controller (start/kill) a background process (server app) in ruby


i'm trying to set up a server for integration tests (specs actually) via ruby and can't figure out how to control the process.

so, what i'm trying to do is:

  1. run a rake task for my gem that executes the integration specs
  2. the task needs to first start a server (i use webrick) and then run the specs
  3. after executing the specs it should kill the webrick so i'm not left with some unused background process

webrick is not a requirement, but it's included in the ruby standard library so being able to use it would be great.

hope anyone is able to help!

ps. i'm running on linux, so having this work for windows is not my main priority (right now).


Solution

  • The standard way is to use the system functions fork (to duplicate the current process), exec (to replace the current process by an executable file), and kill (to send a signal to a process to terminate it).

    For example :

    pid = fork do
      # this code is run in the child process
      # you can do anything here, like changing current directory or reopening STDOUT
      exec "/path/to/executable"
    end
    
    # this code is run in the parent process
    # do your stuffs
    
    # kill it (other signals than TERM may be used, depending on the program you want
    # to kill. The signal KILL will always work but the process won't be allowed
    # to cleanup anything)
    Process.kill "TERM", pid
    
    # you have to wait for its termination, otherwise it will become a zombie process
    # (or you can use Process.detach)
    Process.wait pid
    

    This should work on any Unix like system. Windows creates process in a different way.