class Smith::Daemon

Public Class Methods

new(name, daemonise, dir=nil) click to toggle source
# File lib/smith/daemon.rb, line 13
def initialize(name, daemonise, dir=nil)
  @name = name
  @daemonise = daemonise
  @pid = Daemons::PidFile.new(pid_directory(dir), @name)
end

Public Instance Methods

daemonise() click to toggle source

Daemonise the process if the daemonise option is true, otherwise do nothing.

# File lib/smith/daemon.rb, line 20
def daemonise
  unlink_pid_file

  if @daemonise
    fork && exit

    unless Process.setsid
      raise RuntimeException, 'cannot detach from controlling terminal'
    end

    $0 = @name

    # Be nice to unmount.
    Dir.chdir "/"

    STDIN.reopen("/dev/null")
    STDOUT.reopen("/dev/null")
    STDERR.reopen(STDOUT)
  end

  $0 = @name

  @pid.pid = Process.pid
  logger.debug { "Pid file: #{@pid.filename}" }
end
pid() click to toggle source

Return the pid of the process @return the pid or nil if not set.

# File lib/smith/daemon.rb, line 61
def pid
  @pid.pid
end
running?() click to toggle source

Check to see if the program is running. This checks for the existance of a pid file and if there is checks to see if the pid exists.

# File lib/smith/daemon.rb, line 48
def running?
  pid_files = Daemons::PidFile.find_files(@pid.dir, @name)

  if pid_files.empty?
    false
  else
    pid = File.read(pid_files.first).to_i
    pid > 0 && Daemons::Pid.running?(pid) && process_names_match?(@name, pid)
  end
end

Private Instance Methods

pid_directory(dir) click to toggle source

Get the pid directory. This checks for the command line option, then the config and finally use the tmp directory.

# File lib/smith/daemon.rb, line 89
def pid_directory(dir)
  dir || Utils.check_and_create_directory(Smith.config.agency.pid_directory)
end
process_names_match?(name, pid) click to toggle source

Checks to see if running process that matches the pid in the pid matches the name. @param name [String] the name of the process

@param pid [Integer] the pid of the process

@return true if the running process matches the name

# File lib/smith/daemon.rb, line 82
def process_names_match?(name, pid)
  proc_table = Sys::ProcTable.ps(pid)
  proc_table && proc_table.cmdline == name
end