Module: Adhearsion::CustomDaemonizer

Defined in:
lib/adhearsion/foundation/custom_daemonizer.rb

Instance Method Summary collapse

Instance Method Details

#daemonize(log_file = '/dev/null') ⇒ Object

This method causes the current running process to become a daemon



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

def daemonize(log_file='/dev/null')
  oldmode = 0
  srand # Split rand streams between spawning and daemonized process
  safefork and exit # Fork and exit from the parent

  # Detach from the controlling terminal
  unless sess_id = Process.setsid
    raise 'Cannot detach from controlled terminal'
  end

  # Prevent the possibility of acquiring a controlling terminal
  if oldmode.zero?
    trap 'SIGHUP', 'IGNORE'
    exit if pid = safefork
  end

  Dir.chdir "/"   # Release old working directory
  File.umask 0000 # Ensure sensible umask

  STDIN.reopen "/dev/null"
  STDOUT.reopen '/dev/null', "a"
  STDERR.reopen log_file, "a"
  return oldmode ? sess_id : 0
end

#safeforkObject

Try to fork if at all possible retrying every 5 sec if the maximum process limit for the system has been reached



9
10
11
12
13
14
15
16
17
# File 'lib/adhearsion/foundation/custom_daemonizer.rb', line 9

def safefork
  begin
    pid = fork
    return pid if pid
  rescue Errno::EWOULDBLOCK
    sleep 5
    retry
  end
end