# File lib/daemons/daemonize.rb, line 91
  def daemonize(logfile_name = nil, app_name = nil)
    # Fork and exit from the parent
    safefork and exit

    # 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
    trap 'SIGHUP', 'IGNORE'
    exit if pid = safefork
    
    $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
    
    return sess_id
  end