Given an array of Popen objects returned by the
    pipe method, wait for all processes to terminate
    and return the array with their return values.

    Taken from http://www.enricozini.org/2009/debian/python-pipes/
322312
def pipe_wait(popens):
    
    # Avoid mutating the passed copy
    popens = copy.copy(popens)
    results = [0] * len(popens)
    while popens:
        last = popens.pop(-1)
        results[len(popens)] = last.wait()
    return results
88952
def waiting(self, timeout=0):
        ""
        if self.linebuffer:
            return True
        (winput, woutput, wexceptions) = select.select((self.sock,), (), (), timeout)
        return winput != []
390661
def run(self, args):
        

        # run a subprocess and put the stdout and stderr on the pipe object
        try:
            pipe = subprocess.Popen(
                args,
                stdout=subprocess.PIPE, stderr=subprocess.PIPE,
            )
        except OSError as e:
            if e.errno == errno.ENOENT:
                # File not found.
                # This is equivalent to getting exitcode 127 from sh
                raise exceptions.ShellError(
                    ' '.join(args), 127, '', '',
                )

        # pipe.wait() ends up hanging on large files. using
        # pipe.communicate appears to avoid this issue
        stdout, stderr = pipe.communicate()

        # if pipe is busted, raise an error (unlike Fabric)
        if pipe.returncode != 0:
            raise exceptions.ShellError(
                ' '.join(args), pipe.returncode, stdout, stderr,
            )

        return stdout, stderr
307463
def _flusher_loop(self):
        
        while True:
            pending = []
            pending_size = 0
            try:
                # Block and wait for the flusher to be kicked
                yield self._flush_queue.get()

                # Check whether we should bail first
                if not self.is_connected or self.is_connecting or self.io.closed():
                    break

                # Flush only when we actually have something in buffer...
                if self._pending_size > 0:
                    cmds = b''.join(self._pending)

                    # Reset pending queue and store tmp in case write fails
                    self._pending, pending = [], self._pending
                    self._pending_size, pending_size = 0, self._pending_size
                    yield self.io.write(cmds)
            except tornado.iostream.StreamBufferFullError:
                # Acumulate as pending data size and flush when possible.
                self._pending = pending + self._pending
                self._pending_size += pending_size
            except tornado.iostream.StreamClosedError as e:
                self._pending = pending + self._pending
                self._pending_size += pending_size
                yield self._process_op_err(e)
168612
def terminate_all(wait=False):
        
        for instance in Process.instances:
            if instance.is_running():
                instance.terminate(wait)
1274077
def run_multiple_processes(args_list: List[List[str]],
                           die_on_failure: bool = True) -> None:
    
    for procargs in args_list:
        start_process(procargs)
    # Wait for them all to finish
    wait_for_processes(die_on_failure=die_on_failure)
580940
public static ProcessReturn procWaitWithProcessReturn (Process process, final long timeout) throws OSHelperException {
		long endTime = Calendar.getInstance ().getTimeInMillis () + timeout;

		boolean terminatedByItself = false;

		ProcessReturn processReturn = new ProcessReturn ();
		while (Calendar.getInstance ().getTimeInMillis () < endTime) {
			try {
				InputStream stdoutIs = process.getInputStream ();
				processReturn.stdout = readInputStreamAsString (stdoutIs);

				InputStream stderrIs = process.getErrorStream ();
				processReturn.stderr = readInputStreamAsString (stderrIs);

				processReturn.exitCode = process.exitValue ();
				processReturn.exitStatus = ProcessReturn.osh_PROCESS_EXITED_BY_ITSELF;

				terminatedByItself = true;
			} catch (IllegalThreadStateException ex) {	// the process has not yet terminated
				terminatedByItself = false;
			}
			if (terminatedByItself) {
				break;
			}
		}
		if (!terminatedByItself) {
			process.destroy ();

			try {
				InputStream stdoutIs = process.getInputStream ();
				processReturn.stdout = readInputStreamAsString (stdoutIs);

				InputStream stderrIs = process.getErrorStream ();
				processReturn.stderr = readInputStreamAsString (stderrIs);

				processReturn.exitCode = process.waitFor ();
			} catch (InterruptedException ex) {
				throw new OSHelperException (ex);
			}

			processReturn.exitStatus = ProcessReturn.osh_PROCESS_KILLED_BY_TIMEOUT;
		}

		return processReturn;
	}
1197761
def wait_for_responses(self):
        

        self.thread.join(self.COMMAND_RESPONSE_TIMEOUT_S)
        self.running = False

        return self.responses
506569
async def _cleanup_subprocess(self, process):
        
        if process.returncode is None:
            try:
                process.kill()
                return await asyncio.wait_for(process.wait(), 1)
            except concurrent.futures.TimeoutError:
                self._log.debug('Waiting for process to close failed, may have zombie process.')
            except ProcessLookupError:
                pass
            except OSError:
                if os.name != 'nt':
                    raise
        elif process.returncode > 0:
            raise TSharkCrashException('TShark seems to have crashed (retcode: %d). '
                                       'Try rerunning in debug mode [ capture_obj.set_debug() ] or try updating tshark.'
                                       % process.returncode)
1175796
def run(self):
        '''
        
        '''
        def receive():
            if self.with_communicate:
                self.stdout, self.stderr = self.process.communicate(input=self.stdin)
            elif self.wait:
                self.process.wait()

        if not self.timeout:
            receive()
        else:
            rt = threading.Thread(target=receive)
            rt.start()
            rt.join(self.timeout)
            if rt.isAlive():
                # Subprocess cleanup (best effort)
                self.process.kill()

                def terminate():
                    if rt.isAlive():
                        self.process.terminate()
                threading.Timer(10, terminate).start()
                raise salt.exceptions.TimedProcTimeoutError(
                    '{0} : Timed out after {1} seconds'.format(
                        self.command,
                        six.text_type(self.timeout),
                    )
                )
        return self.process.returncode
1049613
function _pipe(method, args, done) {

  let proc;
  let isProc =
    typeof method === 'object' &&
    (method.constructor && method.constructor.name === 'ChildProcess');

  done = done || function () {};

  if (typeof args === 'function') {
    done = args;
    args = undefined;
  }

  // Ensure args array.
  args = args || [];

  // Allow passing args as a string.
  // supports either ' ' or ', '.
  if (typeof args === 'string') {
    let splitChar = ~args.indexOf(',') ? ',' : ' ';
    if (splitChar === ',')
      args = args.replace(/\s/g, '');
    args = args.split(splitChar);
  }

  // If string assume command set method to spawn.
  if (typeof method === 'string') {
    args = [method, args];
    method = spawn;
  }

  if (isProc)
    proc = method;

  if (!proc)
    proc = method(...args);

  const thru = thruHandler(done);

  proc.stdin = proc.stdin || process.stdin;
  proc.stdout = proc.stdout || process.stdout;
  proc.stderr = proc.stderr || process.stderr;

  proc.stdout.pipe(thru);

  return proc;

}
680723
async def wait_for_read_result(self):
        
        while not self.callback_data:
            await asyncio.sleep(.001)
        rval = self.callback_data
        self.callback_data = []
        return rval
54054
def WaitUntilNoFlowsToProcess(self, timeout=None):
    
    t = self.flow_handler_thread
    if not t:
      return

    start_time = time.time()
    while True:
      with self.lock:
        # If the thread is dead, or there are no requests
        # to be processed/being processed, we stop waiting
        # and return from the function.
        if (not t.isAlive() or
            (not self._GetFlowRequestsReadyForProcessing() and
             not self.flow_handler_num_being_processed)):
          return

      time.sleep(0.2)

      if timeout and time.time() - start_time > timeout:
        raise TimeOutWhileWaitingForFlowsToBeProcessedError(
            "Flow processing didn't finish in time.")
951984
def wait(self):
        

        self.log.debug("acquiring wait lock to wait for completion")
        # using the lock in a with-context blocks, which is what we want if
        # we're running wait()
        with self._wait_lock:
            self.log.debug("got wait lock")
            witnessed_end = False

            if self.exit_code is None:
                self.log.debug("exit code not set, waiting on pid")
                pid, exit_code = no_interrupt(os.waitpid, self.pid, 0) # blocks
                self.exit_code = handle_process_exit_code(exit_code)
                witnessed_end = True

            else:
                self.log.debug("exit code already set (%d), no need to wait",
                        self.exit_code)

            self._quit_threads.set()

            # we may not have a thread for stdin, if the pipe has been connected
            # via _piped="direct"
            if self._input_thread:
                self._input_thread.join()

            # wait, then signal to our output thread that the child process is
            # done, and we should have finished reading all the stdout/stderr
            # data that we can by now
            timer = threading.Timer(2.0, self._stop_output_event.set)
            timer.start()

            # wait for our stdout and stderr streamreaders to finish reading and
            # aggregating the process output
            self._output_thread.join()
            timer.cancel()

            self._background_thread.join()

            if witnessed_end:
                self._process_just_ended()

            return self.exit_code
1230304
def wait(self):
        
        try:
            SpawningProxy(self.containers, abort_on_error=True).wait()
        except Exception:
            # If a single container failed, stop its peers and re-raise the
            # exception
            self.stop()
            raise
152008
def wait(self):
        
        if not self._process_completed:
            self._process_completed = True

            exit_code = self.process.wait()
            if self.process.timed_out:
                # if we timed out, our exit code represents a signal, which is
                # negative, so let's make it positive to store in our
                # TimeoutException
                raise TimeoutException(-exit_code)

            else:
                self.handle_command_exit_code(exit_code)
        
                # if an iterable command is using an instance of OProc for its stdin,
                # wait on it.  the process is probably set to "piped", which means it
                # won't be waited on, which means exceptions won't propagate up to the
                # main thread.  this allows them to bubble up
                if self.process._stdin_process:
                    self.process._stdin_process.command.wait()

        self.log.info("process completed")
        return self
910971
def _get_result(future, pipe, timeout):
    """"""
    counter = count(step=SLEEP_UNIT)

    try:
        while not pipe.poll(SLEEP_UNIT):
            if timeout is not None and next(counter) >= timeout:
                return TimeoutError('Task Timeout', timeout)
            elif future.cancelled():
                return CancelledError()

        return pipe.recv()
    except (EOFError, OSError):
        return ProcessExpired('Abnormal termination')
    except Exception as error:
        return error