# File src/ruby_supportlib/phusion_passenger/vendor/daemon_controller.rb, line 244
  def connect
    connection = nil
    @lock_file.shared_lock do
      begin
        connection = yield
      rescue *ALLOWED_CONNECT_EXCEPTIONS
        connection = nil
      end
    end
    if connection.nil?
      @lock_file.exclusive_lock do
        if !daemon_is_running?
          start_without_locking
        end
        connect_exception = nil
        begin
          connection = yield
        rescue *ALLOWED_CONNECT_EXCEPTIONS => e
          connection = nil
          connect_exception = e
        end
        if connection.nil?
          # Daemon is running but we couldn't connect to it. Possible
          # reasons:
          # - The daemon froze.
          # - Bizarre security restrictions.
          # - There's a bug in the yielded code.
          if connect_exception
            raise ConnectError, "Cannot connect to the daemon: #{connect_exception} (#{connect_exception.class})"
          else
            raise ConnectError, "Cannot connect to the daemon"
          end
        else
          connection
        end
      end
    else
      connection
    end
  end