Method: Daemonize.call_as_daemon

Defined in:
lib/daemons/daemonize.rb

.call_as_daemon(block, logfile_name = nil, app_name = nil) ⇒ Object

Call a given block as a daemon



41
42
43
44
45
46
47
48
49
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
80
81
82
83
84
85
86
87
88
# File 'lib/daemons/daemonize.rb', line 41

def call_as_daemon(block, logfile_name = nil, app_name = nil)
  # we use a pipe to return the PID of the daemon
  rd, wr = IO.pipe

  if tmppid = safefork
    # in the parent

    wr.close
    pid = rd.read.to_i
    rd.close

    Process.waitpid(tmppid)

    return pid
  else
    # in the child

    rd.close

    # Detach from the controlling terminal
    unless Process.setsid
      fail Daemons.RuntimeException.new('cannot detach from controlling terminal')
    end

    # Prevent the possibility of acquiring a controlling terminal
    trap 'SIGHUP', 'IGNORE'
    exit if pid = safefork

    wr.write Process.pid
    wr.close

    $0 = app_name if app_name

    # Release old working directory
    Dir.chdir '/'

    close_io

    redirect_io(logfile_name)

    # Split rand streams between spawning and daemonized process
    srand

    block.call

    exit
  end
end