Fork a background process. Returns the command line used that can be printed if something failed.
194251
private static String fork(String sjavac, String portfile, String logfile, int poolsize, int keepalive,
            final PrintStream err, String stdouterrfile, String background)
            throws IOException, ProblemException {
        if (stdouterrfile != null && stdouterrfile.trim().equals("")) {
            stdouterrfile = null;
        }
        final String startserver = "--startserver:portfile=" + portfile + ",logfile=" + logfile + ",stdouterrfile=" + stdouterrfile + ",poolsize=" + poolsize + ",keepalive="+ keepalive;

        if (background.equals("true")) {
            sjavac += "%20" + startserver;
            sjavac = sjavac.replaceAll("%20", " ");
            sjavac = sjavac.replaceAll("%2C", ",");
            // If the java/sh/cmd launcher fails the failure will be captured by stdouterr because of the redirection here.
            String[] cmd = {"/bin/sh", "-c", sjavac + " >> " + stdouterrfile + " 2>&1"};
            if (!(new File("/bin/sh")).canExecute()) {
                ArrayList<String> wincmd = new ArrayList<String>();
                wincmd.add("cmd");
                wincmd.add("/c");
                wincmd.add("start");
                wincmd.add("cmd");
                wincmd.add("/c");
                wincmd.add(sjavac + " >> " + stdouterrfile + " 2>&1");
                cmd = wincmd.toArray(new String[wincmd.size()]);
            }
            Process pp = null;
            try {
                pp = Runtime.getRuntime().exec(cmd);
            } catch (Exception e) {
                e.printStackTrace(err);
                e.printStackTrace(new PrintWriter(stdouterrfile));
            }
            StringBuilder rs = new StringBuilder();
            for (String s : cmd) {
                rs.append(s + " ");
            }
            return rs.toString();
        }

        // Do not spawn a background server, instead run it within the same JVM.
        Thread t = new Thread() {
            @Override
            public void run() {
                try {
                    JavacServer.startServer(startserver, err);
                } catch (Throwable t) {
                    t.printStackTrace(err);
                }
            }
        };
        t.start();
        return "";
    }
286234
def check_call_out(command):
  
  # start external command process
  p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

  # get outputs
  out, _ = p.communicate()

  # throw exception if process failed
  if p.returncode != 0:
    raise GitInvocationError, 'failed to run "%s"' % " ".join(command)

  return out.strip()
1141103
def execute &block
      raise 'Previous process still exists' unless pipes.empty?

      # clear callbacks
      @callbacks = []
      @errbacks = []

      pid, stdin, stdout, stderr = POSIX::Spawn.popen4 @command.to_s

      @pid = pid
      @stdin  = attach_pipe_handler :stdin, stdin
      @stdout = attach_pipe_handler :stdout, stdout
      @stderr = attach_pipe_handler :stderr, stderr

      if block
        block.call self
      elsif @execution_proc
        @execution_proc.call self
      end
      self
    end
319666
def run_shell(cmd, timeout=60, verbose=False):
    """"""
    retcode = None
    try:
        p = Popen(cmd, shell=True, stdout=PIPE, stderr=STDOUT, executable='/bin/bash')
        continue_running = True
    except Exception as e:
        yield("Failed: %s" % e)
        continue_running = False

    while continue_running:
        try:
            line = p.stdout.readline()
            if verbose and line:
                yield(line)
            elif line.strip():
                yield(line.strip())
        except Exception:
            pass

        try:
            data = irc.recv(4096)
        except Exception as e:
            data = ""
            retcode = p.poll()  # returns None while subprocess is running

        if '!cancel' in data:
            retcode = "Cancelled live output reading. You have to kill the process manually."
            yield "[X]: %s" % retcode
            break

        elif retcode is not None:
            try:
                line = p.stdout.read()
            except:
                retcode = "Too much output, read timed out. Process is still running in background."

            if verbose and line:
                yield line

            if retcode != 0:
                yield "[X]: %s" % retcode
            elif retcode == 0 and verbose:
                yield "[√]"

            break
252585
def system(*args)
      delayer.Deferred.Thread.new {
        Process.waitpid2(Kernel.spawn(*args))
      }.next{|_pid, status|
        if status && status.success?
          status
        else
          raise ForeignCommandAborted.new("command aborted: #{args.join(' ')}", process: status) end
      }
    end
811142
def sendstop(self):
        '''
        
        '''
        if not self.is_started:
            raise EasyProcessError(self, 'process was not started!')

        log.debug('stopping process (pid=%s cmd="%s")', self.pid, self.cmd)
        if self.popen:
            if self.is_alive():
                log.debug('process is active -> sending SIGTERM')

                try:
                    try:
                        self.popen.terminate()
                    except AttributeError:
                        os.kill(self.popen.pid, signal.SIGKILL)
                except OSError as oserror:
                    log.debug('exception in terminate:%s', oserror)

            else:
                log.debug('process was already stopped')
        else:
            log.debug('process was not started')

        return self
375482
private ProcessInfo executeProcess(boolean background,ProcessBuilder pb) 
	{
		try
		{
			
			 pb.directory(workingDirectory);
			 pb.redirectErrorStream(false);
			
			if(log != null)
				pb.redirectOutput(Redirect.appendTo(log));
			
			pb.environment().putAll(envMap);
			Process p = pb.start();

			String out = null;
			String error = null;
			
			if(background)
			{
				out = IO.readText(p.getInputStream(),true,defaultBackgroundReadSize);
				
				error = IO.readText(p.getErrorStream(),true,20);				
			}
			else
			{
				out = IO.readText(p.getInputStream(),true);
				
				error = IO.readText(p.getErrorStream(),true);	
				
			}
				
  	
			if(background)
				return new ProcessInfo(0, out, error);
			
			return new ProcessInfo(p.waitFor(),out,error);
		}
		catch (Exception e)
		{
			return new ProcessInfo(-1, null, Debugger.stackTrace(e));
		}
	}
124700
def _thread_main(self):
        
        _LOGGER.debug("Background thread started.")

        quit_ = False
        while True:
            batch = self._cloud_logger.batch()
            items = _get_many(
                self._queue,
                max_items=self._max_batch_size,
                max_latency=self._max_latency,
            )

            for item in items:
                if item is _WORKER_TERMINATOR:
                    quit_ = True
                    # Continue processing items, don't break, try to process
                    # all items we got back before quitting.
                else:
                    batch.log_struct(**item)

            self._safely_commit_batch(batch)

            for _ in range(len(items)):
                self._queue.task_done()

            if quit_:
                break

        _LOGGER.debug("Background thread exited gracefully.")
1370868
def run_subprocess(command):
    
    x = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out, err = x.communicate()
    out = out.decode('utf-8')
    err = err.decode('utf-8')
    if x.returncode != 0:
        print('STDERR from called program: {}'.format(err))
        print('STDOUT from called program: {}'.format(out))
        raise subprocess.CalledProcessError(x.returncode, command)
    return out, err
425699
def _kill_process(self, pid, sig=signal.SIGKILL):
        """"""
        try:
            os.kill(pid, sig)
        except OSError as e:
            if e.errno == errno.ESRCH: # process itself returned and exited before killing
                logging.debug("Failure %s while killing process %s with signal %s: %s",
                              e.errno, pid, sig, e.strerror)
            else:
                logging.warning("Failure %s while killing process %s with signal %s: %s",
                                e.errno, pid, sig, e.strerror)
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))
441598
def main():
    """"""
    args = docopt(__doc__, version=__version__)
    if args['--print']:
        for section in DEFAULT_OPTIONS:
            print("[{}]".format(section))
            for key, value in DEFAULT_OPTIONS[section].items():
                print("{k} = {v}".format(k=key, v=value))
            print()
        sys.exit(0)

    try:
        config, bird_configuration = load_configuration(args['--file'],
                                                        args['--dir'],
                                                        args['--service-file'])
    except ValueError as exc:
        sys.exit('Invalid configuration: ' + str(exc))

    if args['--check']:
        print("OK")
        sys.exit(0)

    if args['--print-conf']:
        for section in config:
            print("[{}]".format(section))
            for key, value in config[section].items():
                print("{k} = {v}".format(k=key, v=value))
            print()
        sys.exit(0)

    try:
        lock_socket = socket.socket(socket.AF_UNIX, socket.SOCK_DGRAM)
        lock_socket.bind('\0' + "{}".format(PROGRAM_NAME))
    except socket.error as exc:
        sys.exit("failed to acquire a lock by creating an abstract namespace"
                 " socket: {}".format(exc))
    else:
        print("acquired a lock by creating an abstract namespace socket: {}"
              .format(lock_socket))

    # Clean old pidfile, if it exists, and write PID to it.
    pidfile = config.get('daemon', 'pidfile')
    update_pidfile(pidfile)

    # Register our shutdown handler to various termination signals.
    shutdown_handler = partial(shutdown, pidfile)
    signal.signal(signal.SIGHUP, shutdown_handler)
    signal.signal(signal.SIGTERM, shutdown_handler)
    signal.signal(signal.SIGABRT, shutdown_handler)
    signal.signal(signal.SIGINT, shutdown_handler)

    # Set up loggers.
    logger = setup_logger(config)

    # Perform a sanity check on IP-Prefixes
    ip_prefixes_sanity_check(config, bird_configuration)

    # Create our master process.
    checker = healthchecker.HealthChecker(config, bird_configuration)
    logger.info("starting %s version %s", PROGRAM_NAME, __version__)
    checker.run()
930686
def do_bp(self, arg):
        
        pid = self.get_process_id_from_prefix()
        if not self.debug.is_debugee(pid):
            raise CmdError("target process is not being debugged")
        process     = self.get_process(pid)
        token_list  = self.split_tokens(arg, 1, 1)
        try:
            address = self.input_address(token_list[0], pid)
            deferred = False
        except Exception:
            address = token_list[0]
            deferred = True
        if not address:
            address = token_list[0]
            deferred = True
        self.debug.break_at(pid, address)
        if deferred:
            print("Deferred breakpoint set at %s" % address)
        else:
            print("Breakpoint set at %s" % address)
164450
def run_at_subprocess(self, use_subprocess, foo, *args, **kwrags):
        
        if use_subprocess is False:
            return foo(*args, **kwrags)

        child_pid = os.fork()
        if child_pid == 0:
            foo(*args, **kwrags)
            sys.exit(0)
        return os.waitpid(child_pid, 0)[1] == 0
1339968
def background_thread(timeout_fn, timeout_event, handle_exit_code, is_alive,
        quit):
    

    # if there's a timeout event, loop 
    if timeout_event:
        while not quit.is_set():
            timed_out = event_wait(timeout_event, 0.1)
            if timed_out:
                timeout_fn()
                break

    # handle_exit_code will be a function ONLY if our command was NOT waited on
    # as part of its spawning.  in other words, it's probably a background
    # command
    #
    # this reports the exit code exception in our thread.  it's purely for the
    # user's awareness, and cannot be caught or used in any way, so it's ok to
    # suppress this during the tests
    if handle_exit_code and not RUNNING_TESTS: # pragma: no cover
        alive = True
        while alive:
            quit.wait(1)
            alive, exit_code = is_alive()

        handle_exit_code(exit_code)
535896
def spawn_process(self, process=None):
        
        if process is None:
            return False
        # start new child process
        pid = fork()
        if pid != 0:
            # parent process
            process.pid = pid
            self.PROCESSES[process.process_id] = process
            connections.close_all()
            return True
        # child process
        process.pid = getpid()
        # connection.connection.close()
        # connection.connection = None
        process.pre_init_process()
        process.init_process()
        process.run()
        sys.exit(0)
1222707
def run_process(cwd, args):
    """"""
    try:
        process = check_output(args, cwd=cwd, stderr=STDOUT)

        return process
    except CalledProcessError as e:
        log('Uh oh, the teapot broke again! Error:', e, type(e), lvl=verbose, pretty=True)
        log(e.cmd, e.returncode, e.output, lvl=verbose)
        return e.output