Class: Vines::Daemon

Inherits:
Object
  • Object
show all
Defined in:
lib/vines/daemon.rb

Overview

Fork the current process into the background and manage pid files so we can kill the process later.

Instance Method Summary collapse

Constructor Details

#initialize(args) ⇒ Daemon

Configure a new daemon process. Arguments hash can include the following keys: :pid (pid file name, required), :stdin, :stdout, :stderr (default to /dev/null)

Raises:

  • (ArgumentError)


12
13
14
15
16
17
18
# File 'lib/vines/daemon.rb', line 12

def initialize(args)
  @pid = args[:pid]
  raise ArgumentError.new('pid file is required') unless @pid
  raise ArgumentError.new('pid must be a file name') if File.directory?(@pid)
  raise ArgumentError.new('pid file must be writable') unless File.writable?(File.dirname(@pid))
  @stdin, @stdout, @stderr = [:stdin, :stdout, :stderr].map {|k| args[k] || '/dev/null' }
end

Instance Method Details

#pidObject

Returns the numeric process ID from the pid file. If the pid file does not exist, returns nil.



52
53
54
# File 'lib/vines/daemon.rb', line 52

def pid
  File.read(@pid).to_i if File.exists?(@pid) 
end

#running?Boolean

Returns true if the process is running as determined by the numeric pid stored in the pid file created by a previous call to start.

Returns:

  • (Boolean)


39
40
41
42
43
44
45
46
47
48
# File 'lib/vines/daemon.rb', line 39

def running?
  begin
    pid && Process.kill(0, pid)
  rescue Errno::ESRCH
    delete_pid
    false
  rescue Errno::EPERM
    true
  end
end

#startObject

Fork the current process into the background to start the daemon. Do nothing if the daemon is already running.



22
23
24
# File 'lib/vines/daemon.rb', line 22

def start
  daemonize unless running?
end

#stopObject

Use the pid stored in the pid file created from a previous call to start to send a TERM signal to the process. Do nothing if the daemon is not running.



29
30
31
32
33
34
35
# File 'lib/vines/daemon.rb', line 29

def stop
  10.times do
    break unless running?
    Process.kill('TERM', pid)
    sleep(0.1)
  end
end