Class: DaemonChild

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

Overview

Credits

Inspired by and based on Daemonize as distributed as part of Thomas Uehlinger’s Daemons gem.

Daemonize was written by Travis Whitton and is based on Perl’s Proc::Daemonize, which was written by Earl Hood.

Based on the Unix Programmer FAQ which is currently available www.faqs.org/faqs/unix-faq/programmer/faq/ (and other places I’m sure)

Constant Summary collapse

VERSION =
'0.0.1'

Class Method Summary collapse

Class Method Details

.process_nameObject



61
62
63
# File 'lib/daemonchild.rb', line 61

def self.process_name
  $0
end

.process_name=(name) ⇒ Object



65
66
67
# File 'lib/daemonchild.rb', line 65

def self.process_name=(name)
  $0 = name
end

.spawnObject



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
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/daemonchild.rb', line 17

def self.spawn()
  # Exit fast if in app that presents itself as irb
  # as a rudimentary safety check.  if irb daemonizes and gets
  # /dev/null as STDIN, it chews up all the cpu trying to take input
  # but you really shouldn't daemonize irb anyway
  exit if $0 == 'irb'
  
  cwd = Dir.getwd

  # Fork so the parent can exit
  Process.fork and Process.exit

  # Become a process group and session group leader
  sid = Process.setsid

  # Fork so the session group leader can exit and we can not regain
  # a controlling terminal
  Process.fork and Process.exit

  # Return to original working directory
  Dir.chdir cwd
  
  # Give ourselves complete control over permissions of files we'd write
  File.umask 0

  # Close any open filehandles
  ObjectSpace.each_object(IO) do |io|
    begin
      io.close unless io.closed?
    rescue ::Exception
    end
  end

  # Reopen stdin, stdout, stdin to /dev/null
  [STDIN,STDOUT,STDERR].each do |io|
    begin
      io.reopen '/dev/null'
    rescue ::Exception
    end
  end

  return Process.pid
end

.stderr=(fp) ⇒ Object



77
78
79
# File 'lib/daemonchild.rb', line 77

def self.stderr=(fp)
  STDERR.reopen fp
end

.stdin=(fp) ⇒ Object



69
70
71
# File 'lib/daemonchild.rb', line 69

def self.stdin=(fp)
  STDIN.reopen fp
end

.stdout=(fp) ⇒ Object



73
74
75
# File 'lib/daemonchild.rb', line 73

def self.stdout=(fp)
  STDOUT.reopen fp
end