class TaskJuggler::Daemon

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.

Attributes

daemonize[RW]
pidFile[RW]

Public Class Methods

new() click to toggle source
# 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
  # Save the PID of the running daemon as number into this file.
  @pidFile = nil
end

Public Instance Methods

start() click to toggle source

Call this method to turn the process into a background process.

# File lib/taskjuggler/daemon/Daemon.rb, line 36
def start
  return 0 unless @daemonize

  # Fork and have the parent exit
  if (pid = fork) == -1
    fatal('first_fork_failed', 'First fork failed')
  elsif !pid.nil?
    # This is the parent. We can exit now.
    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
    fatal('second_fork_failed', 'Second fork failed')
  elsif !pid.nil?
    # This is the parent. We can exit now.
    debug('', "Forked a child process with PID #{pid}")
    exit! 0
  end

  @pid = Process.pid

  writePidFile

  # 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)

  info('daemon_pid',
       "The process is running as daemon now with PID #{@pid}")

  0
end
stop() click to toggle source

This method may provide some cleanup functionality in the future. You better call it before you exit.

# File lib/taskjuggler/daemon/Daemon.rb, line 81
def stop
  if @pidFile
    begin
      File.delete(@pidFile)
    rescue
      warning('cannot_delete_pidfile',
              "Cannote delete the PID file (#{@pidFile}): #{$!}")
    end
    info('daemon_deleted_pidfile', "PID file #{@pidFile} deleted")
  end
end