Class: Smith::Daemon

Inherits:
Object
  • Object
show all
Includes:
Logger
Defined in:
lib/smith/daemon.rb

Instance Method Summary collapse

Methods included from Logger

included

Constructor Details

#initialize(name, daemonise, dir = nil) ⇒ Daemon

Returns a new instance of Daemon.



14
15
16
17
18
# File 'lib/smith/daemon.rb', line 14

def initialize(name, daemonise, dir=nil)
  @name = name
  @daemonise = daemonise
  @pid = Daemons::PidFile.new(pid_directory(dir), @name)
end

Instance Method Details

#daemoniseObject

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



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
# File 'lib/smith/daemon.rb', line 21

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

#pidObject

Return the pid of the process

Returns:

  • the pid or nil if not set.



62
63
64
# File 'lib/smith/daemon.rb', line 62

def pid
  @pid.pid
end

#running?Boolean

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.

Returns:

  • (Boolean)


49
50
51
52
53
54
55
56
57
58
# File 'lib/smith/daemon.rb', line 49

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


66
67
68
69
70
71
72
# File 'lib/smith/daemon.rb', line 66

def unlink_pid_file
  p = Pathname.new(@pid.filename)
  if p.exist?
    logger.verbose { "Removing pid file: #{p.to_s}" }
    p.unlink
  end
end