Module: Adhearsion::CustomDaemonizer

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

Class Method Summary collapse

Class Method Details

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

This method causes the current running process to become a daemon



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
49
50
# File 'lib/adhearsion/foundation/custom_daemonizer.rb', line 22

def self.daemonize(log_file = '/dev/null')
  srand # Split rand streams between spawning and daemonized process

  # Fork, then exit when the child has exited below
  if pid = safefork
    ::Process.wait pid
    exit
  end

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

  # Prevent the possibility of acquiring a controlling terminal
  # Fork again, allow a PID file to be written, then exit
  trap 'SIGHUP', 'IGNORE'

  if pid = safefork
    yield pid if block_given?
    exit
  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 sess_id
end

.safeforkObject

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



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

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