Module: DaemonSpawn

Defined in:
lib/daemon_spawn.rb

Overview

Large portions of this were liberally stolen from the ‘simple-daemon’ project at simple-daemon.rubyforge.org/

Defined Under Namespace

Classes: Base

Class Method Summary collapse

Class Method Details

.start(daemon, args) ⇒ Object

:nodoc:



14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/daemon_spawn.rb', line 14

def self.start(daemon, args) #:nodoc:
  if !File.writable?(File.dirname(daemon.log_file))
    STDERR.puts "Unable to write log file to #{daemon.log_file}"
    exit 1
  end

  if !File.writable?(File.dirname(daemon.pid_file))
    STDERR.puts "Unable to write PID file to #{daemon.pid_file}"
    exit 1
  end

  if daemon.alive? && daemon.singleton
    STDERR.puts "An instance of #{daemon.app_name} is already " +
      "running (PID #{daemon.pid})"
    exit 0
  end

  fork do
    Process.setsid
    exit if fork
    open(daemon.pid_file, 'w') { |f| f << Process.pid }
    Dir.chdir daemon.working_dir
    File.umask 0000
    log = File.new(daemon.log_file, "a")
    log.sync = daemon.sync_log
    STDIN.reopen "/dev/null"
    STDOUT.reopen log
    STDERR.reopen STDOUT
    trap("TERM") {daemon.stop; exit}
    daemon.start(args)
  end
  puts "#{daemon.app_name} started."
end

.status(daemon) ⇒ Object

:nodoc:



63
64
65
# File 'lib/daemon_spawn.rb', line 63

def self.status(daemon) #:nodoc:
  puts "#{daemon.app_name} is #{daemon.alive? ? "" : "NOT "}running (PID #{daemon.pid})"
end

.stop(daemon) ⇒ Object

:nodoc:



48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/daemon_spawn.rb', line 48

def self.stop(daemon) #:nodoc:
  if pid = daemon.pid
    FileUtils.rm(daemon.pid_file)
    Process.kill("TERM", pid)
    begin
      Process.wait(pid)
    rescue Errno::ECHILD
    end
  else
    puts "PID file not found. Is the daemon started?"
  end
rescue Errno::ESRCH
  puts "PID file found, but process was not running. The daemon may have died."
end

.usage(msg = nil) ⇒ Object

:nodoc:



7
8
9
10
11
12
# File 'lib/daemon_spawn.rb', line 7

def self.usage(msg=nil) #:nodoc:
  print "#{msg}, " if msg
  puts "usage: #{$0} <command> [options]"
  puts "Where <command> is one of start, stop, restart or status"
  puts "[options] are additional options passed to the underlying process"
end