Module: Daemon::Controller

Defined in:
lib/chocolate_rain/daemon.rb

Class Method Summary collapse

Class Method Details

.daemonize(daemon) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
# File 'lib/chocolate_rain/daemon.rb', line 27

def self.daemonize(daemon)
  case !ARGV.empty? && ARGV[0]
  when 'start'
    start(daemon)
  when 'stop'
    stop(daemon)
  when 'restart'
    stop(daemon)
    start(daemon)
  else
    puts "Invalid command. Please specify start, stop or restart."
    exit
  end
end

.start(daemon) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/chocolate_rain/daemon.rb', line 42

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



57
58
59
60
61
62
63
64
65
# File 'lib/chocolate_rain/daemon.rb', line 57

def self.stop(daemon)
  if !File.file?(daemon.pid_fn)
    puts "Pid file not found. Is the daemon started?"
    exit
  end
  pid = PidFile.recall(daemon)
  FileUtils.rm(daemon.pid_fn)
  pid && Process.kill("TERM", pid)
end