def _await_socket(self, timeout):
    """Blocks for the nailgun subprocess to bind and emit a listening port in the nailgun stdout."""
    with safe_open(self._ng_stdout, 'r') as ng_stdout:
      start_time = time.time()
      accumulated_stdout = ''
      while 1:
        # TODO: share the decreasing timeout logic here with NailgunProtocol.iter_chunks() by adding
        # a method to pants.util.contextutil!
        remaining_time = time.time() - (start_time + timeout)
        if remaining_time > 0:
          stderr = read_file(self._ng_stderr, binary_mode=True)
          raise self.InitialNailgunConnectTimedOut(
            timeout=timeout,
            stdout=accumulated_stdout,
            stderr=stderr,
          )

        readable, _, _ = select.select([ng_stdout], [], [], (-1 * remaining_time))
        if readable:
          line = ng_stdout.readline()                          # TODO: address deadlock risk here.
          try:
            return self._NG_PORT_REGEX.match(line).group(1)
          except AttributeError:
            pass
          accumulated_stdout += line
Blocks for the nailgun subprocess to bind and emit a listening port in the nailgun stdout.