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

.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.



31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/serverside/daemon.rb', line 31

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
    stop(daemon)
    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.



46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/serverside/daemon.rb', line 46

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.



62
63
64
65
66
# File 'lib/serverside/daemon.rb', line 62

def self.stop(daemon)
  pid = PidFile.recall(daemon)
  FileUtils.rm(daemon.pid_fn)
  pid && Process.kill("TERM", pid)
end