# File lib/daemons/daemonize.rb, line 201
  def daemonize(logfile_name = nil, app_name = nil)
    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 Daemons.RuntimeException.new('cannot detach from controlling terminal')
    end

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

    $0 = app_name if app_name
    
    Dir.chdir "/"   # Release old working directory
    File.umask 0000 # Insure sensible umask

    # Make sure all file descriptors are closed
    ObjectSpace.each_object(IO) do |io|
      unless [STDIN, STDOUT, STDERR].include?(io)
        begin
          unless io.closed?
            io.close
          end
        rescue ::Exception
        end
      end
    end

    redirect_io(logfile_name)
    
    #return oldmode ? sess_id : 0   # Return value is mostly irrelevant
    return sess_id
  end