Start processes and check their status. When some process crashes,
        start it again. *max_restarts* is maximum amount of the restarts
        across all processes. *processes* is a :class:`list` of the
        :class:`ProcessWrapper` instances.
774203
def start_processes(self, max_restarts=-1):
        
        while 1:
            for process in self.processes:
                if not process:
                    # When process has not been started, start it
                    if not process.has_started:
                        process.start()
                        continue
                    # When process has stopped, start it again
                    exitcode = process.exitcode
                    if exitcode != 0:
                        # Process has been signaled or crashed
                        if exitcode > 0:
                            self.logger.error(
                                "Process '%s' with pid %d died with exitcode "
                                "%d", process.name, process.pid, exitcode
                            )
                        else:
                            self.logger.error(
                                "Process '%s' with pid %d died due to %s",
                                process.name, process.pid,
                                SIGNALS_TO_NAMES_DICT[abs(exitcode)]
                            )
                        # Max restarts has been reached, exit
                        if not max_restarts:
                            self.logger.fatal("Too many child restarts")
                            break
                        # Start process again
                        process.start()
                        # Decrement max_restarts counter
                        if max_restarts > 0:
                            max_restarts -= 1
                    else:
                        # Process has stopped without error
                        self.logger.info(
                            "Process '%s' with pid %d has stopped",
                            process.name, process.pid
                        )
                        # Start process again
                        process.start()
                        self.logger.info(
                            "Process '%s' has been started with pid %d",
                            process.name, process.pid
                        )
            else:
                time.sleep(0.25)
                continue
            break
1182618
def status(self):
        

        if self.pid is None:
            self.pid = self.read_pid()
        if self.pid is None:
            sp = BackgroundProcess.objects.filter(pk=1).first()
            if sp:
                self.pid = sp.pid
        if self.pid is None or self.pid == 0:
            self.stderr.write("%s: can't determine process id exiting.\n" % datetime.now().isoformat(' '))
            return False
        if self.pid != getpid():
            # calling from outside the daemon instance
            try:
                kill(self.pid, signal.SIGUSR2)
                return True
            except OSError as e:
                if e.errno == errno.ESRCH:
                    return False
                else:
                    return False

        process_list = []
        for process in BackgroundProcess.objects.filter(parent_process__pk=self.process_id):
            process_list.append(process)
            process_list += list(process.backgroundprocess_set.filter())
        for process in process_list:
            logger.debug('%s, parrent process_id %d' % (self.label, process.parent_process.pk))
            logger.debug('%s, process_id %d' % (self.label, self.process_id))
314457
function restartProcessing (q) {
  logger('restartProcessing')
  setTimeout(function randomRestart () {
    queueProcess.restart(q)
  }, Math.floor(Math.random() * 1000))
}
1017645
def restart_with_reloader():
    
    cwd = os.getcwd()
    args = _get_args_for_reloading()
    new_environ = os.environ.copy()
    new_environ["SANIC_SERVER_RUNNING"] = "true"
    cmd = " ".join(args)
    worker_process = Process(
        target=subprocess.call,
        args=(cmd,),
        kwargs={"cwd": cwd, "shell": True, "env": new_environ},
    )
    worker_process.start()
    return worker_process
1080494
def restart
      Procodile.log(@process.log_color, description, "Restarting using #{@process.restart_mode} mode")
      update_pid
      case @process.restart_mode
      when 'usr1', 'usr2'
        if running?
          ::Process.kill(@process.restart_mode.upcase, @pid)
          @tag = @supervisor.tag if @supervisor.tag
          Procodile.log(@process.log_color, description, "Sent #{@process.restart_mode.upcase} signal to process #{@pid}")
        else
          Procodile.log(@process.log_color, description, "Process not running already. Starting it.")
          on_stop
          new_instance = @process.create_instance(@supervisor)
          new_instance.port = self.port
          new_instance.start
        end
        self
      when 'start-term'
        new_instance = @process.create_instance(@supervisor)
        new_instance.start
        stop
        new_instance
      when 'term-start'
        stop
        new_instance = @process.create_instance(@supervisor)
        new_instance.port = self.port
        Thread.new do
          sleep 0.5 while running?
          new_instance.start
        end
        new_instance
      end
    end
91681
@Override
    public ManagedProcess waitForExitMaxMsOrDestroy(long maxWaitUntilDestroyTimeout)
            throws ManagedProcessException {
        waitForExitMaxMs(maxWaitUntilDestroyTimeout);
        if (isAlive()) {
            logger.info("Process didn't exit within max. {}ms, so going to destroy it now: {}",
                    maxWaitUntilDestroyTimeout, getProcLongName());
            destroy();
        }
        return this;
    }
700239
function restart() {
	logger.log('Restarting', clc.green(script));
	notifyWebSocket('restart');
	if (!kill(true)) {
		// The process wasn't running, start it now.
		start(true);
	} /*else {
		// The process will restart when its 'exit' event is emitted.
	}*/
}
211458
def check_alive_instances(self):
        
        # Only for external
        for instance in self.instances:
            if instance in self.to_restart:
                continue

            if instance.is_external and instance.process and not instance.process.is_alive():
                logger.error("The external module %s died unexpectedly!", instance.name)
                logger.info("Setting the module %s to restart", instance.name)
                # We clean its queues, they are no more useful
                instance.clear_queues(self.daemon.sync_manager)
                self.set_to_restart(instance)
                # Ok, no need to look at queue size now
                continue

            # Now look for maximum queue size. If above the defined value, the module may have
            # a huge problem and so bailout. It's not a perfect solution, more a watchdog
            # If max_queue_size is 0, don't check this
            if self.daemon.max_queue_size == 0:
                continue

            # Check for module queue size
            queue_size = 0
            try:
                queue_size = instance.to_q.qsize()
            except Exception:  # pylint: disable=broad-except
                pass
            if queue_size > self.daemon.max_queue_size:
                logger.error("The module %s has a too important queue size (%s > %s max)!",
                             instance.name, queue_size, self.daemon.max_queue_size)
                logger.info("Setting the module %s to restart", instance.name)
                # We clean its queues, they are no more useful
                instance.clear_queues(self.daemon.sync_manager)
                self.set_to_restart(instance)
1024648
boolean isProcessTreeOverLimit(ProcfsBasedProcessTree pTree, 
                                    String tId, long limit) {
    long currentMemUsage = pTree.getCumulativeVmem();
    // as processes begin with an age 1, we want to see if there are processes
    // more than 1 iteration old.
    long curMemUsageOfAgedProcesses = pTree.getCumulativeVmem(1);
    return isProcessTreeOverLimit(tId, currentMemUsage, 
                                  curMemUsageOfAgedProcesses, limit);
  }
374635
def stop_process(parser_args):
    
    from synergy.system import process_helper

    try:
        pid = process_helper.get_process_pid(parser_args.process_name)
        if pid is None or process_helper.poll_process(parser_args.process_name) is False:
            message = 'ERROR: Process {0} is already terminated {1}\n'.format(parser_args.process_name, pid)
            sys.stderr.write(message)
            sys.exit(1)

        process_helper.kill_process(parser_args.process_name)
    except Exception as e:
        sys.stderr.write('Exception on killing {0} : {1}\n'.format(parser_args.process_name, e))
        traceback.print_exc(file=sys.stderr)
1234396
def _wait_for_process(self, p, shell=False):
        
        local_maxmem = -1
        sleeptime = .5
        while p.poll() is None:
            if not shell:
                local_maxmem = max(local_maxmem, self._memory_usage(p.pid) / 1e6)
                # print("int.maxmem (pid:" + str(p.pid) + ") " + str(local_maxmem))
            time.sleep(sleeptime)
            sleeptime = min(sleeptime + 5, 60)

        self.peak_memory = max(self.peak_memory, local_maxmem)
        
        del self.procs[p.pid]

        info = "Process " + str(p.pid) + " returned: (" + str(p.returncode) + ")."
        if not shell:
            info += " Peak memory: (Process: " + str(round(local_maxmem, 3)) + "GB;"
            info += " Pipeline: " + str(round(self.peak_memory, 3)) + "GB)\n"

        print(info + "\n")
        if p.returncode != 0:
            raise Exception("Process returned nonzero result.")
        return [p.returncode, local_maxmem]
199464
def main():
    
    start_time = datetime.now()
    output_q = Queue(maxsize=20)

    procs = []
    for a_device in devices:
        my_proc = Process(target=show_version_queue, args=(a_device, output_q))
        my_proc.start()
        procs.append(my_proc)

    # Make sure all processes have finished
    for a_proc in procs:
        a_proc.join()

    while not output_q.empty():
        my_dict = output_q.get()
        for k, val in my_dict.items():
            print(k)
            print(val)

    print("\nElapsed time: " + str(datetime.now() - start_time))
814560
protected function _processes()
    {
        $process = glob('/proc/*/status', GLOB_NOSORT);
        if (is_array($process) && (($total = count($process)) > 0)) {
            $processes['*'] = 0;
            $buf = "";
            for ($i = 0; $i < $total; $i++) {
                if (CommonFunctions::rfts($process[$i], $buf, 0, 4096, false)) {
                    $processes['*']++; //current total
                    if (preg_match('/^State:\s+(\w)/m', $buf, $state)) {
                        if (isset($processes[$state[1]])) {
                            $processes[$state[1]]++;
                        } else {
                            $processes[$state[1]] = 1;
                        }
                    }
                }
            }
            if (!($processes['*'] > 0)) {
                $processes['*'] = $processes[' '] = $total; //all unknown
            }
            $this->sys->setProcesses($processes);
        }
    }
1266986
def start(self, stdout=subprocess.PIPE, stderr=subprocess.PIPE):
        
        if self.pre_start_check():
            # Some other executor (or process) is running with same config:
            raise AlreadyRunning(self)

        if self.process is None:
            command = self.command
            if not self._shell:
                command = self.command_parts

            env = os.environ.copy()
            env[ENV_UUID] = self._uuid
            popen_kwargs = {
                'shell': self._shell,
                'stdin': subprocess.PIPE,
                'stdout': stdout,
                'stderr': stderr,
                'universal_newlines': True,
                'env': env,
            }
            if platform.system() != 'Windows':
                popen_kwargs['preexec_fn'] = os.setsid
            self.process = subprocess.Popen(
                command,
                **popen_kwargs,
            )

        self._set_timeout()

        self.wait_for(self.check_subprocess)
        return self
940214
def restart_process(self, pid):
        '''
        
        '''
        if self._restart_processes is False:
            return
        log.info(
            'Process %s (%s) died with exit status %s, restarting...',
            self._process_map[pid]['tgt'],
            pid,
            self._process_map[pid]['Process'].exitcode
        )
        # don't block, the process is already dead
        self._process_map[pid]['Process'].join(1)

        self.add_process(self._process_map[pid]['tgt'],
                         self._process_map[pid]['args'],
                         self._process_map[pid]['kwargs'])

        del self._process_map[pid]
238638
def loop(self, max_seconds=None):
        
        loop_started =  datetime.datetime.now()

        self._is_running = True
        while self._is_running:
            self.process_error_queue(self.q_error)

            if max_seconds is not None:
                if (datetime.datetime.now() - loop_started).total_seconds() > max_seconds:
                    break
            for subprocess in self._subprocesses:
                if not subprocess.is_alive():
                    subprocess.start()

            self.process_io_queue(self.q_stdout, sys.stdout)
            self.process_io_queue(self.q_stderr, sys.stderr)
807175
def restartIndyPool(**kwargs):
    ''''''
    print("Restarting...")
    try:
      stopIndyPool()
      startIndyPool()
      print("...restarted")
    except Exception as exc:
      eprint("...failed to restart")
      raise exc