Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@fogus
Created September 14, 2011 12:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save fogus/1216429 to your computer and use it in GitHub Desktop.
Save fogus/1216429 to your computer and use it in GitHub Desktop.
Double fork a Ruby process.
raise 'Must run as root' if Process.euid != 0
p1 = Process.fork {
# p1 is now running independent of, and parallel to the calling process
Process.setsid
p2 = Process.fork {
# p2 is now running independent of, and parallel to p1
$0 = 'mydaemon'
pidfile = File.new('/var/run/mydaemon.pid', 'w')
pidfile.chmod( 0644 )
pidfile.puts "#{Process.pid}"
pidfile.close
logfile = File.new('/var/log/mydaemon.log', 'a')
logfile.chmod( 0644 )
logfile.puts("Starting as pid: #{Process.pid}")
logfile.fsync
Dir.chdir '/'
File.umask 0000
STDIN.reopen '/dev/null'
STDOUT.reopen '/dev/null', 'a'
STDERR.reopen STDOUT
Signal.trap("USR1") do
logfile.puts "You sent me a USR1 signal"
logfile.fsync
end
loop {
sleep(1) # daemon will wake every second...
# .. to process handler code here
}
}
raise 'Fork failed!' if p2 == -1
Process.detach(p2) # divorce p2 from parent process (p1)
}
raise 'Fork failed!' if p1 == -1
Process.detach(p1) # divorce p1 from parent process (shell)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment