| Class | TaskJuggler::Daemon |
| In: |
lib/taskjuggler/daemon/Daemon.rb
|
| Parent: | Object |
This class provides the basic functionality to turn the current process into a background process (daemon). To use it, derive you main class from this class and call the start() method.
| daemonize | [RW] | |
| log | [R] |
# File lib/taskjuggler/daemon/Daemon.rb, line 26 def initialize # You can set this flag to false to prevent the program from # disconnecting from the current terminal. This is useful for debugging # purposes. @daemonize = true @log = LogFile.instance end
Call this method to turn the process into a background process.
# File lib/taskjuggler/daemon/Daemon.rb, line 35 def start return unless @daemonize # Fork and have the parent exit if (pid = fork) == -1 @log.fatal('First fork failed') elsif !pid.nil? # This is the parent. We can exit now. @log.debug("Forked a child process with PID #{pid}") exit! 0 end # Create a new session Process.setsid # Fork again to make sure we lose the controlling terminal if (pid = fork) == -1 @log.fatal('Second fork failed') elsif !pid.nil? # This is the parent. We can exit now. @log.debug("Forked a child process with PID #{pid}") exit! 0 end @pid = Process.pid # Change current working directory to the file system root Dir.chdir '/' # Make sure we can create files with any permission File.umask 0 # We no longer have a controlling terminal, so these are useless. $stdin.reopen('/dev/null') $stdout.reopen('/dev/null', 'a') $stderr.reopen($stdout) @log.info("The process is running as daemon now with PID #{@pid}") 0 end