Class: TinyDaemon

Inherits:
Object
  • Object
show all
Defined in:
lib/tiny_daemon.rb,
lib/tiny_daemon/version.rb,
lib/tiny_daemon/process_file.rb

Defined Under Namespace

Classes: ProcessFile

Constant Summary collapse

START_TIMEOUT =
5
STOP_TIMEOUT =
30
VERSION =
'0.0.2'

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app_name, pid_dir, log_dir) ⇒ TinyDaemon

Returns a new instance of TinyDaemon.



10
11
12
13
14
# File 'lib/tiny_daemon.rb', line 10

def initialize(app_name, pid_dir, log_dir)
  @app_name = app_name
  @pid_dir = pid_dir
  @log_dir = log_dir
end

Instance Attribute Details

#app_nameObject

Returns the value of attribute app_name.



5
6
7
# File 'lib/tiny_daemon.rb', line 5

def app_name
  @app_name
end

#log_dirObject

Returns the value of attribute log_dir.



5
6
7
# File 'lib/tiny_daemon.rb', line 5

def log_dir
  @log_dir
end

#pid_dirObject

Returns the value of attribute pid_dir.



5
6
7
# File 'lib/tiny_daemon.rb', line 5

def pid_dir
  @pid_dir
end

Instance Method Details

#exit(&block) ⇒ Object



16
17
18
# File 'lib/tiny_daemon.rb', line 16

def exit(&block)
  @exit_block = block
end

#processObject



20
21
22
# File 'lib/tiny_daemon.rb', line 20

def process
  @process ||= ProcessFile.new(self.app_name, self.pid_dir)
end

#start(&block) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/tiny_daemon.rb', line 24

def start(&block)
  raise "#{self.process.pid_file_path} already exists. The process might already run. Remove it manually if it doesn't." if self.process.get
  
  Process.fork do
    Process.daemon(true, true)

    self.process.store(Process.pid)
    reset_umask
    set_process_name
    redirect_io

    if @exit_block
      trap("TERM") { exit_on_double_signals } # If `kill <pid>` is called, it will be trapped here
    end

    at_exit { clean_process_file }
    block.call
  end

  wait_until_start
  self.process.get
end

#stop(timeout_secs = STOP_TIMEOUT) ⇒ Object



47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/tiny_daemon.rb', line 47

def stop(timeout_secs = STOP_TIMEOUT)
  pid = self.process.get

  if pid
    begin
      Process.kill('TERM', pid)
    rescue => e
    end

    wait_until_exit(pid, timeout_secs)
  end
end