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

    # Detach from the controlling terminal
    unless sess_id = 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 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

    sess_id
  end