Module: Deadpool::Daemonizer

Included in:
Server
Defined in:
lib/deadpool/daemonizer.rb

Instance Method Summary collapse

Instance Method Details

#daemonize(opts = {}) ⇒ Object



11
12
13
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
47
48
# File 'lib/deadpool/daemonizer.rb', line 11

def daemonize(opts={})
  opts = { :log => '/dev/null', :pid => "/var/run/#{File.basename($0)}.pid" }.merge(opts)

  $stdout.sync = $stderr.sync = true
  $stdin.reopen("/dev/null")

  exit if fork

  Process.setsid

  exit if fork

  Dir.chdir("/") if opts[:chdir]
  File.umask(0000) if opts[:umask]

  if File.exist?(opts[:pid])
    begin
      existing_pid = File.read(opts[:pid]).to_i
      Process.kill(0, existing_pid) # See if proc exists
      abort "error: existing process #{existing_pid} using this pidfile, exiting"
    rescue Errno::ESRCH
      puts "warning: removing stale pidfile with pid #{existing_pid}"
    end
  end

  File.open(opts[:pid], 'w') { |f| f.write($$) }

  at_exit do
    ( File.read(opts[:pid]).to_i == $$ and File.unlink(opts[:pid]) ) rescue nil
  end

  puts "forked process is #{$$}"
  puts "output redirected to #{opts[:log]}"

  $stdout.reopen(opts[:log], 'a')
  $stderr.reopen(opts[:log], 'a')
  $stdout.sync = $stderr.sync = true
end

#kill(opts = {}) ⇒ Object



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
# File 'lib/deadpool/daemonizer.rb', line 50

def kill(opts={})
  begin
    opts = { :log => "/dev/null", :pid => "/var/run/#{File.basename($0)}.pid" }.merge(opts)
    pid = File.read(opts[:pid]).to_i
    sec = 60 # Seconds to wait before force killing
    Process.kill("TERM", pid)

    begin
      SystemTimer.timeout(sec) do
        loop do
          puts "waiting #{sec} seconds for #{pid} before sending KILL"
          Process.kill(0, pid) # See if proc exists

          sec -= 1
          sleep 1
        end
      end
    rescue Errno::ESRCH
      puts "killed process #{pid}"
    rescue Timeout::Error
      Process.kill("KILL", pid)
      puts "force killed process #{pid}"
    end

  rescue Errno::ENOENT
    puts "warning: pidfile #{opts[:pid]} does not exist"
  rescue Errno::ESRCH
    puts "warning: process #{pid} does not exist"
  end
end