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.



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

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.



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

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

#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)


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

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)
  end
end


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

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