/*
Fork a server process process and wait for server to come around
540057
public static void fork(String sjavacCmd, PortFile portFile, int poolsize, int keepalive)
            throws IOException, InterruptedException {
        List<String> cmd = new ArrayList<>();
        cmd.addAll(Arrays.asList(OptionHelper.unescapeCmdArg(sjavacCmd).split(" ")));
        cmd.add("--startserver:"
              + "portfile=" + portFile.getFilename()
              + ",poolsize=" + poolsize
              + ",keepalive="+ keepalive);

        Process serverProcess;
        Log.debug("Starting server. Command: " + String.join(" ", cmd));
        try {
            // If the cmd for some reason can't be executed (file is not found,
            // or is not executable for instance) this will throw an
            // IOException and p == null.
            serverProcess = new ProcessBuilder(cmd)
                    .redirectErrorStream(true)
                    .start();
        } catch (IOException ex) {
            // Message is typically something like:
            // Cannot run program "xyz": error=2, No such file or directory
            Log.error("Failed to create server process: " + ex.getMessage());
            Log.debug(ex);
            throw new IOException(ex);
        }

        // serverProcess != null at this point.
        try {
            // Throws an IOException if no valid values materialize
            portFile.waitForValidValues();
        } catch (IOException ex) {
            // Process was started, but server failed to initialize. This could
            // for instance be due to the JVM not finding the server class,
            // or the server running in to some exception early on.
            Log.error("Sjavac server failed to initialize: " + ex.getMessage());
            Log.error("Process output:");
            Reader serverStdoutStderr = new InputStreamReader(serverProcess.getInputStream());
            try (BufferedReader br = new BufferedReader(serverStdoutStderr)) {
                br.lines().forEach(Log::error);
            }
            Log.error("<End of process output>");
            try {
                Log.error("Process exit code: " + serverProcess.exitValue());
            } catch (IllegalThreadStateException e) {
                // Server is presumably still running.
            }
            throw new IOException("Server failed to initialize: " + ex.getMessage(), ex);
        }
    }
577252
function runWebServerInProcess(rawConfig, serverConfig, emitter) {
  var server = require('./server.js');
  
  if (serverConfig.command == 'stop') {
    logger.info('stopping server');
    return server.stop();
  }
  
  var app = server.listen(rawConfig, serverConfig, function(err, newCommandName, newConfig, finalCallback) {
    if (err) { 
      logger.error("Error: " + err);
      if (callback) callback(err);
    } else {
      emitter.emit(newCommandName, newConfig, finalCallback);
    }
  });
}
969724
function processServeQueue() {
      while (serveQueue.length) {
        const item = serveQueue.shift();
        _serveFile(item.file, item.done);
        // It is possible start compiling while in release.
        if (state.compilationCompleted !== _currentState) {
          break;
        }
      }
    }
346761
def asynchronous(self, fun, low, user='UNKNOWN', pub=None):
        '''
        
        '''
        async_pub = pub if pub is not None else self._gen_async_pub()

        proc = salt.utils.process.SignalHandlingMultiprocessingProcess(
                target=self._proc_function,
                args=(fun, low, user, async_pub['tag'], async_pub['jid']))
        with salt.utils.process.default_signals(signal.SIGINT, signal.SIGTERM):
            # Reset current signals before starting the process in
            # order not to inherit the current signal handlers
            proc.start()
        proc.join()  # MUST join, otherwise we leave zombies all over
        return async_pub
703363
private ProcessResult waitFor(WaitForProcess task) throws IOException, InterruptedException, TimeoutException {
    ProcessResult result;
    if (timeout == null) {
      // Use the current thread
      result = task.call();
    }
    else {
      // Fork another thread to invoke Process.waitFor()
      ExecutorService service = newExecutor(task);
      // Copy values to not conflict with further executions
      long _timeout = timeout;
      TimeUnit unit = timeoutUnit;
      try {
        result = invokeSubmit(service, task).get(_timeout, unit);
      }
      catch (ExecutionException e) {
        Throwable c = e.getCause();
        if (c instanceof IOException) {
          throw (IOException) c;
        }
        if (c instanceof InterruptedException) {
          throw (InterruptedException) c;
        }
        if (c instanceof InvalidExitValueException) {
          InvalidExitValueException i = (InvalidExitValueException) c;
          throw new InvalidExitValueException(i.getMessage(), i.getResult());
        }
        if (c instanceof InvalidOutputException) {
          InvalidOutputException i = (InvalidOutputException) c;
          throw new InvalidOutputException(i.getMessage(), i.getResult());
        }
        if (c.getClass().equals(InvalidResultException.class)) {
          InvalidResultException p = (InvalidResultException) c;
          throw new InvalidResultException(p.getMessage(), p.getResult());
        }
        throw new IllegalStateException("Error occured while waiting for process to finish:", c);
      }
      catch (TimeoutException e) {
        messageLogger.message(log, "{} is running too long", task);
        throw newTimeoutException(_timeout, unit, task);
      }
      finally {
        // Interrupt the task if it's still running and release the ExecutorService's resources
        service.shutdownNow();
      }
    }
    return result;
  }
738555
function fork() {
            cluster.fork().on('message', function(message) {
                if (message.cmd === 'restart' && message.pid && restartQueue.indexOf(message.pid) === -1) {
                    // When worker asks to restart gracefully in cluster, then add it to restart queue.
                    log('Cluster graceful shutdown: queued. pid=' + message.pid);
                    restartQueue.push(message.pid);
                    checkRestartQueue();
                }
            });
        }
1160032
def fork_many(n)
      pids = []
      n.times do |i|
        pids << fork do
          yield i
          Kernel.exit!
        end
      end

      pids.each { |pid| ::Process.wait(pid) }
    end
1207073
function processQueue(){
      try {
        // mark queue as processing to avoid concurrency
        processing = true;

        // process queue
        var item;
        while (item = queue.shift())
          item.fn.call(item.context);
      } finally {
        // queue is not processing anymore
        processing = false;

        // if any function in queue than exception was occured,
        // run rest functions in next code frame
        if (queue.length)
          timer = setImmediate(process);
      }
    }
1248170
function process(doc, cb) {
    freeze()
    assertParser('process', processor.Parser)
    assertCompiler('process', processor.Compiler)

    if (!cb) {
      return new Promise(executor)
    }

    executor(null, cb)

    function executor(resolve, reject) {
      var file = vfile(doc)

      pipeline.run(processor, {file: file}, done)

      function done(err) {
        if (err) {
          reject(err)
        } else if (resolve) {
          resolve(file)
        } else {
          cb(null, file)
        }
      }
    }
  }
470337
def post_fork_child(self, fingerprint, jvm_options, classpath, stdout, stderr):
    """"""
    java = SubprocessExecutor(self._distribution)

    subproc = java.spawn(classpath=classpath,
                         main='com.martiansoftware.nailgun.NGServer',
                         jvm_options=jvm_options,
                         args=[':0'],
                         stdin=safe_open('/dev/null', 'r'),
                         stdout=safe_open(self._ng_stdout, 'w'),
                         stderr=safe_open(self._ng_stderr, 'w'),
                         close_fds=True)

    self.write_pid(subproc.pid)
1138283
def wait_process(self):
        """"""
        self.process.wait()
        if self.analyze_data:
            self.receiving_thread.join()
639415
def _orphan_this_process(cls, wait_for_parent=False):
        """"""
        # The current PID will be the PPID of the forked child
        ppid = os.getpid()

        pid = os.fork()
        if pid > 0:
            # Exit parent
            sys.exit(0)

        if wait_for_parent and cls._pid_is_alive(ppid, timeout=1):
            raise DaemonError(
                'Parent did not exit while trying to orphan process')
398008
function checkPid(pid, callback) {
  var list, msg = '';
  var isWin = _.isWin();
  var serverInfo = util.serverInfo() || options;

  if (isWin) {
    list = spawn('tasklist');
  } else {
    list = spawn('ps', ['-A']);
  }

  list.stdout.on('data', function(chunk) {
    msg += chunk.toString('utf-8').toLowerCase();
  });

  list.on('exit', function() {
    var found = false;
    msg.split(/[\r\n]+/).forEach(function(item) {

      if (~item.indexOf('--type ' + serverInfo.type) || process.platform !== 'darwin') {
        var m = item.match(/\d+/);

        if (m && m[0] == pid) {
          found = true;
        }
      }
    });

    callback(found);
  });

  list.on('error', function(e) {
    if (isWin) {
      fis.log.error('fail to execute `tasklist` command, please add your system path (eg: C:\\Windows\\system32, you should replace `C` with your system disk) in %PATH%');
    } else {
      fis.log.error('fail to execute `ps` command.');
    }
  });
}
921245
def server_thread(sock, handle_conn, quit_event):
    """"""
    log.debug('server thread started')

    def accept_connection():
        conn, _ = sock.accept()
        conn.settimeout(None)
        return conn

    while True:
        log.debug('waiting for connection on %s', sock.getsockname())
        try:
            conn = retry(accept_connection, socket.timeout, quit_event)
        except StopIteration:
            log.debug('server stopped')
            break
        # Handle connections from SSH concurrently.
        threading.Thread(target=handle_conn,
                         kwargs=dict(conn=conn)).start()
    log.debug('server thread stopped')
1278308
async function _spawn(exe, args, options) {
    return new Promise((resolve, reject) => {
        try {
            const process = spawn(exe, args, options);
            process.on('error', error => {
                reject(error);
            });
            process.unref();
            if (process.pid !== undefined) {
                resolve(true);
            }
        } catch (error) {
            reject(error);
        }
    })
}
1178973
def make_server(host, port, app=None, threaded=False, processes=1,
                request_handler=None, passthrough_errors=False,
                ssl_context=None):
    
    if threaded and processes > 1:
        raise ValueError("cannot have a multithreaded and "
                         "multi process server.")
    elif threaded:
        return ThreadedWSGIServer(host, port, app, request_handler,
                                  passthrough_errors, ssl_context)
    elif processes > 1:
        return ForkingWSGIServer(host, port, app, processes, request_handler,
                                 passthrough_errors, ssl_context)
    else:
        return BaseWSGIServer(host, port, app, request_handler,
                              passthrough_errors, ssl_context)
51743
def process_request(self, request, client_address):
        """"""
        self.collect_children()
        pid = os.fork()  # @UndefinedVariable
        if pid:
            # Parent process
            if self.active_children is None:
                self.active_children = []
            self.active_children.append(pid)
            self.close_request(request) #close handle in parent process
            return
        else:
            # Child process.
            # This must never return, hence os._exit()!
            try:
                self.finish_request(request, client_address)
                self.shutdown_request(request)
                os._exit(0)
            except:
                try:
                    self.handle_error(request, client_address)
                    self.shutdown_request(request)
                finally:
                    os._exit(1)