Module: Daemon

Defined in:
lib/serverside/daemon.rb,
lib/serverside/cluster.rb

Overview

The Daemon module takes care of starting and stopping daemons.

Defined Under Namespace

Modules: PidFile Classes: Base, Cluster

Constant Summary collapse

WorkingDirectory =
FileUtils.pwd

Class Method Summary collapse

Class Method Details

.alive?(daemon) ⇒ Boolean

Returns:

  • (Boolean)


76
77
78
79
# File 'lib/serverside/daemon.rb', line 76

def self.alive?(daemon)
  pid = PidFile.recall(daemon) rescue nil
  pid ? Process.exists?(pid) : false
end

.control(daemon, cmd = nil) ⇒ Object

Controls a daemon according to the supplied command or command-line parameter. If an invalid command is specified, an error is raised.



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/serverside/daemon.rb', line 35

def self.control(daemon, cmd = nil)
  case (cmd || (!ARGV.empty? && ARGV[0]) || :nil).to_sym
  when :start
    start(daemon)
  when :stop
    stop(daemon)
  when :restart
    begin
      stop(daemon)
      sleep 2
    rescue
    end
    start(daemon)
  else
    raise 'Invalid command. Please specify start, stop or restart.'
  end
end

.start(daemon) ⇒ Object

Starts the daemon by forking and bcoming session leader.



54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/serverside/daemon.rb', line 54

def self.start(daemon)
  fork do
    Process.setsid
    exit if fork
    PidFile.store(daemon, Process.pid)
    Dir.chdir WorkingDirectory
    File.umask 0000
    STDIN.reopen "/dev/null"
    STDOUT.reopen "/dev/null", "a"
    STDERR.reopen STDOUT
    trap("TERM") {daemon.stop; exit}
    daemon.start
  end
end

.stop(daemon) ⇒ Object

Stops the daemon by sending it a TERM signal.



70
71
72
73
74
# File 'lib/serverside/daemon.rb', line 70

def self.stop(daemon)
  pid = PidFile.recall(daemon)
  pid && Process.kill("TERM", pid) rescue nil
  PidFile.remove(daemon)
end