Created
September 14, 2011 12:24
-
-
Save fogus/1216429 to your computer and use it in GitHub Desktop.
Double fork a Ruby process.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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