CodeShop

rails's daemonize

March 29th, 2009

Isn’t this a nice and clean way of forking?

1
2
3
4
5
6
7
8
9
10
def daemonize
  exit if fork                   # Parent exits, child continues.
  Process.setsid                 # Become session leader.
  exit if fork                   # Zap session leader. See [1].
  Dir.chdir "/"                  # Release old working directory.
  File.umask 0000                # Ensure sensible umask. Adjust as needed.
  STDIN.reopen "/dev/null"       # Free file descriptors and
  STDOUT.reopen "/dev/null", "a" # point them somewhere sensible.
  STDERR.reopen STDOUT           # STDOUT/ERR should better go to a logfile.
end

That is, it’s the same as in Steven’s Advanced Programming for the Unix Environment, but a lot less verbose. Then again, above is Ruby – Stevens is C.

Sorry, comments are closed for this article.