# 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