Class: Archfiend::Daemon

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

Constant Summary collapse

DEV_NULL =
'/dev/null'.freeze

Class Method Summary collapse

Class Method Details

.close_ioObject



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/archfiend/daemon.rb', line 50

def close_io
  ObjectSpace.each_object(IO) do |io|
    next if [$stdin, $stdout, $stderr].include?(io)

    begin
      io.close
    rescue
      nil
    end
  end
  3.upto(8192) do |i|
    begin
      IO.for_fd(i).close
    rescue
      nil
    end
  end
end

.daemonize(pid_file:, log_file:, app_name:, app_env:) ⇒ Object



6
7
8
9
10
11
12
13
# File 'lib/archfiend/daemon.rb', line 6

def daemonize(pid_file:, log_file:, app_name:, app_env:)
  Process.daemon(nil, true) # Don't close descriptors
  handle_pid_file(pid_file)
  close_io
  redirect_std_io(log_file)
  set_process_title(app_name, app_env)
  srand
end

.handle_pid_file(pid_file) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/archfiend/daemon.rb', line 19

def handle_pid_file(pid_file)
  if File.exist?(pid_file)
    msg = "Pid file #{pid_file} already exists, the daemon is already running or " \
      "didn't shut down properly. \nRemove the pid file and try again."
    Process.abort(msg)
  end

  daemon_pid = Process.pid
  begin
    File.open(pid_file, 'w') { |f| f.puts daemon_pid }
  rescue
    msg = "Pid file creation failed, no permissions to write to #{pid_file}."
    Process.abort(msg)
  end
  at_exit do
    next unless Process.pid == daemon_pid

    begin
      File.unlink(pid_file)
    rescue
      nil
    end
  end
end

.redirect_std_io(log_file) ⇒ Object



44
45
46
47
48
# File 'lib/archfiend/daemon.rb', line 44

def redirect_std_io(log_file)
  redirect_stdin
  redirect_stdout(log_file)
  redirect_stderr
end

.set_process_title(app_name, app_env) ⇒ Object



15
16
17
# File 'lib/archfiend/daemon.rb', line 15

def set_process_title(app_name, app_env)
  Process.setproctitle "#{app_name} (#{app_env})"
end