Home

Awesome

Build Status Code Climate endorse

preforker

A gem to easily create protocol agnostic prefork servers.

Example

Let's see an example using the Mac 'say' command.

  require 'rubygems'
  require 'preforker'

  #At this point we can open some socket or reserve any other resource you want to share with your workers.
  #Whatever we do before Preforker.new is ran only in the master process.
  say `hi, I\\'m the master`

  Preforker.new(:timeout => 10) do |master|
    #this block is only run by each worker (10 by default)

    #first you should write the code that is needed to be ran
    #once when a new fork is created, initializations, etc.
    `say hi, I\\'m a worker`

    #now you could IO.select a socket, run an EventMachine service (see example), or as we do here,
    #just run a worker loop. Notice that you need to ask master if it wants you alive periodically or
    #else it will kill you after the timeout elapses. Respect your master!
    while master.wants_me_alive? do
      sleep 1
      `say ping pong`
    end

    #here we can do whatever we want to exit gracefully
    `say bye`


  #here we are using #start to daemonize. We could have used #run to just block and then send the INT signal with ctrl-c to stop
  end.start

  puts "I'm the launcher that forked off master, bye bye"
  puts "To kill the server just do: kill -s QUIT `cat preforker.pid`"

Remember that to kill the server you need to:

  kill -s QUIT `cat preforker.pid`

See the examples directory and the specs for more examples.

Why? I can always use threads!

As always, it's a matter of trade offs, so it depends on how you ponder the advantages and disadvantages of a preforking architecture for your particular case. Still notice that you could have a mix of threads and processes, they are independent concepts.

###Advantages

###Disadvantages

Configuration options

Signals

You can send some signals to master to control the way it handles the workers lifetime.

Installation

  gem install preforker

Acknowledgments

Most of the preforking operating system tricks come from Unicorn. I checked out its source code and read this great introduction by @rtomayko.

To do list

Note on Patches/Pull Requests

Copyright

Copyright (c) 2012 Daniel Cadenas. See LICENSE for details.