fork worker with certain settings
328650
function forkWorker(settings, env) {
    if (settings) {
      cluster.settings = settings;
      cluster.setupMaster();
    }
    return cluster.fork(env);
  }
1254769
protected static function forkOneWorkerForLinux($worker)
    {
        // Get available worker id.
        $id = static::getId($worker->workerId, 0);
        if ($id === false) {
            return;
        }
        $pid = pcntl_fork();
        // For master process.
        if ($pid > 0) {
            static::$_pidMap[$worker->workerId][$pid] = $pid;
            static::$_idMap[$worker->workerId][$id]   = $pid;
        } // For child processes.
        elseif (0 === $pid) {
            srand();
            mt_srand();
            if ($worker->reusePort) {
                $worker->listen();
            }
            if (static::$_status === static::STATUS_STARTING) {
                static::resetStd();
            }
            static::$_pidMap  = array();
            // Remove other listener.
            foreach(static::$_workers as $key => $one_worker) {
                if ($one_worker->workerId !== $worker->workerId) {
                    $one_worker->unlisten();
                    unset(static::$_workers[$key]);
                }
            }
            Timer::delAll();
            static::setProcessTitle('WorkerMan: worker process  ' . $worker->name . ' ' . $worker->getSocketName());
            $worker->setUserAndGroup();
            $worker->id = $id;
            $worker->run();
            $err = new Exception('event-loop exited');
            static::log($err);
            exit(250);
        } else {
            throw new Exception("forkOneWorker fail");
        }
    }
1313594
def with_fork_context(self, func):
    """"""
    res = self._native.lib.scheduler_fork_context(self._scheduler, Function(self._to_key(func)))
    return self._raise_or_return(res)
1325922
function WorkerFn(root) {
  var timers = {};

  root.onmessage = function (event) {
    switch (event.data.type) {
      case 'ping':
        root.postMessage({ type: 'pong' });
        break;

      case 'set_timeout':
        timers[event.data.id] = setTimeout(function () {
          root.postMessage({ type: 'tick', id: event.data.id });
        }, event.data.delay);
        break;

      case 'clear_timeout':
        clearTimeout(timers[event.data.id]);
        break;

      case 'set_interval':
        timers[event.data.id] = setInterval(function () {
          root.postMessage({ type: 'tick', id: event.data.id });
        }, event.data.interval);
        break;

      case 'clear_interval':
        clearInterval(timers[event.data.id]);
        break;
    }
  };
}
408911
def _daemonize(self):
        
        LOGGER.info('Forking %s into the background', sys.argv[0])

        # Write the pidfile if current uid != final uid
        if os.getuid() != self.uid:
            fd = open(self.pidfile_path, 'w')
            os.fchmod(fd.fileno(), 0o644)
            os.fchown(fd.fileno(), self.uid, self.gid)
            fd.close()

        try:
            pid = os.fork()
            if pid > 0:
                    sys.exit(0)
        except OSError as error:
                raise OSError('Could not fork off parent: %s', error)

        # Set the user id
        if self.uid != os.getuid():
            os.setuid(self.uid)

        # Set the group id
        if self.gid != os.getgid():
            try:
                os.setgid(self.gid)
            except OSError as error:
                LOGGER.error('Could not set group: %s', error)

        # Decouple from parent environment
        os.chdir('/')
        os.setsid()
        os.umask(0o022)

        # Fork again
        try:
            pid = os.fork()
            if pid > 0:
                sys.exit(0)
        except OSError as error:
            raise OSError('Could not fork child: %s', error)

        # redirect standard file descriptors
        sys.stdout.flush()
        sys.stderr.flush()
        si = open(os.devnull, 'r')
        so = open(os.devnull, 'a+')
        se = open(os.devnull, 'a+')
        os.dup2(si.fileno(), sys.stdin.fileno())
        os.dup2(so.fileno(), sys.stdout.fileno())
        os.dup2(se.fileno(), sys.stderr.fileno())

        # Automatically call self._remove_pidfile when the app exits
        atexit.register(self._remove_pidfile)
        self._write_pidfile()
774368
def pre_fork(self, _):
        '''
        
        '''
        if 'aes' not in salt.master.SMaster.secrets:
            # TODO: This is still needed only for the unit tests
            # 'tcp_test.py' and 'zeromq_test.py'. Fix that. In normal
            # cases, 'aes' is already set in the secrets.
            salt.master.SMaster.secrets['aes'] = {
                'secret': multiprocessing.Array(
                    ctypes.c_char,
                    salt.utils.stringutils.to_bytes(salt.crypt.Crypticle.generate_key_string())
                ),
                'reload': salt.crypt.Crypticle.generate_key_string
            }
670532
def scale_down_dynos(self):
        
        processes = ["web", "worker"]
        if self.clock_is_on:
            processes.append("clock")
        for process in processes:
            self.scale_down_dyno(process)
567303
def setWorkerInfo(self, hostname, workerAmount, origin):
        """"""

        scoop.logger.debug('Initialising {0}{1} worker {2} [{3}].'.format(
            "local" if hostname in utils.localHostnames else "remote",
            " origin" if origin else "",
            self.workersLeft,
            hostname,
            )
        )

        add_args, add_kwargs = self._setWorker_args(origin)
        self.workers[-1].setWorker(*add_args, **add_kwargs)
        self.workers[-1].setWorkerAmount(workerAmount)
615872
def startup
      enable_gc_optimizations
      if Thread.current == Thread.main
        register_signal_handlers
        prune_dead_workers
      end
      run_hook :before_first_fork
      register_worker

      # Fix buffering so we can `rake resque:work > resque.log` and
      # get output from the child in there.
      $stdout.sync = true
    end
1273281
function startWorker(triggeredByError=false){
    return new Promise(function(resolve){
        // default restart delay
        let restartDelay = 0;

        // worker restart because of died process ?
        if (triggeredByError === true){
            // increment restart counter
            _restartCounter++;
        }

        // delayed restart ?
        if (_restartCounter > 10){
            // calculate restart delay (min: 2s)
            restartDelay = 200 * _restartCounter;

            // trigger alert message
            _logger.alert(`delayed worker-restart of ${restartDelay/1000}s - number of failed processes: ${_restartCounter}`);
        }

        // trigger async fork
        setTimeout(() => {
            // create a new child process
            // note: this method RELOADS the entire js file/module! - it is NOT a classical process.fork() !
            // this allows you to hot-reload your application by restarting the workers
            const worker = _cluster.fork();

            // return worker
            resolve(worker);

        }, restartDelay);
    });
}
1171505
function Pool(script, options) {
  if (typeof script === 'string') {
    this.script = script || null;
  }
  else {
    this.script = null;
    options = script;
  }

  this.workers = [];  // queue with all workers
  this.tasks = [];    // queue with tasks awaiting execution

  options = options || {};

  this.forkArgs = options.forkArgs || [];
  this.forkOpts = options.forkOpts || {};
  this.debugPortStart = (options.debugPortStart || 43210);
  this.nodeWorker = options.nodeWorker;

  // configuration
  if (options && 'maxWorkers' in options) {
    validateMaxWorkers(options.maxWorkers);
    this.maxWorkers = options.maxWorkers;
  }
  else {
    this.maxWorkers = Math.max((environment.cpus || 4) - 1, 1);
  }

  if (options && 'minWorkers' in options) {
    if(options.minWorkers === 'max') {
      this.minWorkers = Math.max((environment.cpus || 4) - 1, 1);
    } else {
      validateMinWorkers(options.minWorkers);
      this.minWorkers = options.minWorkers;
      this.maxWorkers = Math.max(this.minWorkers, this.maxWorkers);     // in case minWorkers is higher than maxWorkers
    }
    this._ensureMinWorkers();
  }

  this._boundNext = this._next.bind(this);


  if (this.nodeWorker === 'thread') {
    WorkerHandler.ensureWorkerThreads();
  }
}
523804
def _thread_worker_fn(samples, batchify_fn, dataset):
    """"""
    if isinstance(samples[0], (list, tuple)):
        batch = [batchify_fn([dataset[i] for i in shard]) for shard in samples]
    else:
        batch = batchify_fn([dataset[i] for i in samples])
    return batch
166183
def run_command_as_worker(self, command, after_post_fork_hook=False):
        
        self._set('worker-exec2' if after_post_fork_hook else 'worker-exec', command, multi=True)

        return self._section
748114
function reserveWorker(workerType, callback) {
        var debug = false,
            execArgv = process.execArgv.filter(function (arg) {
                if (arg.indexOf('--debug-brk') === 0) {
                    debug = '--debug-brk';
                } else if (arg.indexOf('--debug') === 0) {
                    debug = '--debug';
                } else if (arg.indexOf('--inspect-brk') === 0) {
                    debug = '--inspect-brk';
                } else if (arg.indexOf('--inspect') === 0) {
                    debug = '--inspect';
                } else {
                    return true;
                }

                return false;
            });
        // http://stackoverflow.com/questions/16840623/how-to-debug-node-js-child-forked-process
        // For some reason --debug-brk is given here..
        if (debug) {
            logger.info('Main process is in debug mode [', debug, ']');
            execArgv.push(debug + '=' + debugPort.toString());
            logger.info('Child debug port: ' + debugPort.toString());
            debugPort += 2;
        }

        logger.debug('execArgv for main process', process.execArgv);
        logger.debug('execArgv for new child process', execArgv);

        if (Object.keys(_workers || {}).length < gmeConfig.server.maxWorkers) {
            var childProcess = Child.fork(SIMPLE_WORKER_JS, [], {execArgv: execArgv});

            _workers[childProcess.pid] = {
                childProcess: childProcess,
                state: CONSTANTS.workerStates.initializing,
                type: workerType,
                cb: null
            };

            logger.debug('workerPid forked ' + childProcess.pid);
            childProcess.on('message', function (msg) {
                messageHandling(msg);

                // FIXME: Do we really need the "initialize" in addition to "initialized"?
                // FIXME: Why couldn't the worker start the initializing at spawn? (It can load the gmeConfig itself)
                if (msg.type === CONSTANTS.msgTypes.initialized && typeof callback === 'function') {
                    callback();
                    callback = null;
                }
            });

            childProcess.on('exit', function (code, signal) {
                logger.debug('worker has exited: ' + childProcess.pid);
                // When killing child-process the code is undefined and the signal SIGINT.
                if (code !== 0 && signal !== 'SIGINT') {
                    logger.warn('worker ' + childProcess.pid + ' has exited abnormally with code ' + code +
                        ', signal', signal);
                    if (typeof callback === 'function') {
                        callback(new Error('worker ' + childProcess.pid + ' exited abnormally with code ' + code));
                    }
                } else {
                    logger.debug('worker ' + childProcess.pid + ' was terminated.');
                }

                delete _workers[childProcess.pid];
                reserveWorkerIfNecessary(workerType);
            });
        } else if (typeof callback === 'function') {
            callback();
        }
    }
482527
function(brk) {
		hooks.enableHooks(
			brk,
			function(module, port) {
				grunt.log.ok('Debugging forked process %s on port %d', module, port);
			}
		);
	}
114041
function(settings, callback) {
    "use strict";

    if (typeof settings === 'function') {
      callback = settings;
      settings = {};
    }

    if (typeof settings === 'undefined') {
      settings = {};
    }

    if (typeof callback !== 'function') {
      callback = function () {};
    }

    getLogFiles(function () {
      parseOptions(settings, function () {
        setupLogger();

        require('./Logger').verbose('Starting worker manager');

        // Start the Master
        master = require('./master');

        registerListeners(master);

        master.start();

        callback();
      });
    });
  }
271253
def post_fork_child(self):
    """"""
    # The server finds run-specific info dirs by looking at the subdirectories of info_dir,
    # which is conveniently and obviously the parent dir of the current run's info dir.
    info_dir = os.path.dirname(self.context.run_tracker.run_info_dir)

    settings = ReportingServer.Settings(info_dir=info_dir,
                                        root=get_buildroot(),
                                        template_dir=self.options.template_dir,
                                        assets_dir=self.options.assets_dir,
                                        allowed_clients=self.options.allowed_clients)

    server = ReportingServer(self.options.port, settings)

    self.write_socket(server.server_port())

    # Block forever.
    server.start()