Post-fork() child callback for ProcessManager.daemon_spawn().
965628
def post_fork_child(self):
    """"""
    entry_point = '{}:launch'.format(__name__)
    exec_env = combined_dict(os.environ, dict(PANTS_ENTRYPOINT=entry_point))
    # Pass all of sys.argv so that we can proxy arg flags e.g. `-ldebug`.
    cmd = [sys.executable] + sys.argv
    self._logger.debug('cmd is: PANTS_ENTRYPOINT={} {}'.format(entry_point, ' '.join(cmd)))
    # TODO: Improve error handling on launch failures.
    os.spawnve(os.P_NOWAIT, sys.executable, cmd, env=exec_env)
519929
def spawn(command)
      fork do
        File.umask self.umask if self.umask
        uid_num = Etc.getpwnam(self.uid).uid if self.uid
        gid_num = Etc.getgrnam(self.gid).gid if self.gid
        gid_num = Etc.getpwnam(self.uid).gid if self.gid.nil? && self.uid

        ::Dir.chroot(self.chroot) if self.chroot
        ::Process.setsid
        ::Process.groups = [gid_num] if gid_num
        ::Process.initgroups(self.uid, gid_num) if self.uid && gid_num
        ::Process::Sys.setgid(gid_num) if gid_num
        ::Process::Sys.setuid(uid_num) if self.uid
        self.dir ||= '/'
        Dir.chdir self.dir
        $0 = command
        STDIN.reopen "/dev/null"
        if self.log_cmd
          STDOUT.reopen IO.popen(self.log_cmd, "a")
        else
          STDOUT.reopen file_in_chroot(self.log), "a"
        end
        if err_log_cmd
          STDERR.reopen IO.popen(err_log_cmd, "a")
        elsif err_log && (log_cmd || err_log != log)
          STDERR.reopen file_in_chroot(err_log), "a"
        else
          STDERR.reopen STDOUT
        end

        # close any other file descriptors
        3.upto(256){|fd| IO::new(fd).close rescue nil}

        if self.env && self.env.is_a?(Hash)
          self.env.each do |(key, value)|
            ENV[key] = value.to_s
          end
        end

        exec command unless command.empty?
      end
    end
1014315
def pre_fork(self, process_manager, kwargs=None):
        '''
        
        '''
        process_manager.add_process(self._publish_daemon, kwargs=kwargs)
888488
function spawn() {
    startInterval();
    var args = Array.prototype.slice.call(arguments);
    if (currentCount < limitCount) {
        currentCount++;
        if (monitorCallback) {
            monitorCallback("start", remainedTasks);
        }
        return new Promise(function (resolved) {
            var process = originalSpawn.apply(null, args);
            process.on("close", function (code) {
                if (monitorCallback) {
                    monitorCallback("close", remainedTasks, code);
                }
                currentCount--;
                if (currentCount === 0 && remainedTasks.length === 0) {
                    callWaitAllCallbacks();
                }
            });
            resolved(process);
        });
    } else {
        var id = taskId++;
        remainedTasks.push([args, id]);
        if (monitorCallback) {
            monitorCallback("added", remainedTasks);
        }
        return new Promise(function (resolved) {
            remainedTaskCallbacks[id] = resolved;
        });
    }
}
193631
def reopen_after_fork!
      # ok, we know that only the child process calls this, right?
      return false unless (@state == :running) or (@state == :paused)
      logger.debug { "#{self.class}##{__method__}" }

      @state = :running
      @mutex = Mutex.new
      @cond  = ConditionVariable.new
      @queue = []
      prune_dead_threads
      spawn_threadpool
    end
929221
def spawn(argv, master_read=_read, stdin_read=_read):
    """"""
    if type(argv) == type(''):
        argv = (argv,)
    pid, master_fd = fork()
    if pid == CHILD:
        try:
            os.execlp(argv[0], *argv)
        except:
            # If we wanted to be really clever, we would use
            # the same method as subprocess() to pass the error
            # back to the parent.  For now just dump stack trace.
            traceback.print_exc()
        finally:
            os._exit(1)
    try:
        mode = tty.tcgetattr(STDIN_FILENO)
        tty.setraw(STDIN_FILENO)
        restore = 1
    except tty.error:    # This is the same as termios.error
        restore = 0
    try:
        _copy(master_fd, master_read, stdin_read)
    except OSError:
        # Some OSes never return an EOF on pty, just raise
        # an error instead.
        pass
    finally:
        if restore:
            tty.tcsetattr(STDIN_FILENO, tty.TCSAFLUSH, mode)

    os.close(master_fd)
    return os.waitpid(pid, 0)[1]
730473
function signalKill(childProcess, callback) {
  childProcess.emit('signalKill');
  if (IS_WINDOWS) {
    const taskkill = spawn('taskkill', ['/F', '/T', '/PID', childProcess.pid]);
    taskkill.on('exit', (exitStatus) => {
      if (exitStatus) {
        return callback(
          new Error(`Unable to forcefully terminate process ${childProcess.pid}`)
        );
      }
      callback();
    });
  } else {
    childProcess.kill('SIGKILL');
    process.nextTick(callback);
  }
}
798060
function spawn() {
  if(this.ps && this.ps.connected) return;
  this.ps = fork(
    runner, [], {execPath: path.basename(process.execPath)});
  this.ps.send({event: 'loglevel', level: log.level()});
}
587688
public function daemonize()
    {
        $pid = pcntl_fork();

        if ($pid === -1) {
            throw new \RuntimeException('Unable to fork child process.');
        } else if ($pid) {
            exit;
        }

        // Make sub process as session leader
        posix_setsid();

        if ($pid === -1) {
            throw new \RuntimeException('Unable to fork child process.');
        } else if ($pid) {
            exit;
        }

        // Prepare the resource
        $this->prepared = false;
        $pid = posix_getpid();
        $this->ppid = $this->pid;
        $this->pid = $pid;
        $this->queue = null;
        $this->process = new Process($this, $this->pid, $this->ppid);
        $this->children = array();
        $this->prepared = true;

        return $this;
    }
416627
def create_process(daemon, name, callback, *callbackParams):
    
    bp = Process(daemon=daemon, name=name, target=callback, args=callbackParams)
    return bp
1159936
protected function spawnIPCThread()
    {
        if (FileSystem::$supported) {
            eio_event_loop();
        }
        $thread = new IPC;
        $this->ipcthreads->push($thread);

        $this->callbacks->push(function ($self) use ($thread) {
            $thread->start();
            $pid = $thread->getPid();
            if ($pid < 0) {
                Daemon::$process->log('could not fork IPCThread');
            } elseif ($pid === 0) { // worker
                $this->log('Unexcepted execution return to outside of Thread->start()');
                exit;
            }
        });
        if (EventLoop::$instance) {
            EventLoop::$instance->interrupt();
        }
        return true;
    }
1216558
def _threaded_callback(callback, *args):
    
    t = Thread(target=callback, args=args)
    t.daemon = True
    t.start()
607089
def run(self):
        '''
        
        '''
        salt.utils.process.appendproctitle(self.__class__.__name__)

        # init things that need to be done after the process is forked
        self._post_fork_init()

        # Make Start Times
        last = int(time.time())

        old_present = set()
        while True:
            now = int(time.time())
            if (now - last) >= self.loop_interval:
                salt.daemons.masterapi.clean_old_jobs(self.opts)
                salt.daemons.masterapi.clean_expired_tokens(self.opts)
                salt.daemons.masterapi.clean_pub_auth(self.opts)
                salt.daemons.masterapi.clean_proc_dir(self.opts)
            self.handle_git_pillar()
            self.handle_schedule()
            self.handle_key_cache()
            self.handle_presence(old_present)
            self.handle_key_rotate(now)
            salt.utils.verify.check_max_open_files(self.opts)
            last = now
            time.sleep(self.loop_interval)
467183
def start(self):
        """"""
        if self.worker is None:
            raise DaemonError('No worker is defined for daemon')

        if os.environ.get('DAEMONOCLE_RELOAD'):
            # If this is actually a reload, we need to wait for the
            # existing daemon to exit first
            self._emit_message('Reloading {prog} ... '.format(prog=self.prog))
            # Orhpan this process so the parent can exit
            self._orphan_this_process(wait_for_parent=True)
            pid = self._read_pidfile()
            if (pid is not None and
                    self._pid_is_alive(pid, timeout=self.stop_timeout)):
                # The process didn't exit for some reason
                self._emit_failed()
                message = ('Previous process (PID {pid}) did NOT '
                           'exit during reload').format(pid=pid)
                self._emit_error(message)
                self._shutdown(message, 1)

        # Check to see if the daemon is already running
        pid = self._read_pidfile()
        if pid is not None:
            # I don't think this should not be a fatal error
            self._emit_warning('{prog} already running with PID {pid}'.format(
                prog=self.prog, pid=pid))
            return

        if not self.detach and not os.environ.get('DAEMONOCLE_RELOAD'):
            # This keeps the original parent process open so that we
            # maintain control of the tty
            self._fork_and_supervise_child()

        if not os.environ.get('DAEMONOCLE_RELOAD'):
            # A custom message is printed for reloading
            self._emit_message('Starting {prog} ... '.format(prog=self.prog))

        self._setup_environment()

        if self.detach:
            self._detach_process()
        else:
            self._emit_ok()

        if self.pidfile is not None:
            self._write_pidfile()

        # Setup signal handlers
        signal.signal(signal.SIGINT, self._handle_terminate)
        signal.signal(signal.SIGQUIT, self._handle_terminate)
        signal.signal(signal.SIGTERM, self._handle_terminate)

        self._run()
80991
def pre_fork(self, process_manager):
        '''
        
        '''
        salt.transport.mixins.auth.AESReqServerMixin.pre_fork(self, process_manager)
        if USE_LOAD_BALANCER:
            self.socket_queue = multiprocessing.Queue()
            process_manager.add_process(
                LoadBalancerServer, args=(self.opts, self.socket_queue)
            )
        elif not salt.utils.platform.is_windows():
            self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
            self._socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
            _set_tcp_keepalive(self._socket, self.opts)
            self._socket.setblocking(0)
            self._socket.bind((self.opts['interface'], int(self.opts['ret_port'])))
1073487
public function daemonize() {

        // fork script
        $pid = $this->fork();

        // detach from current terminal (if any)
        $this->detach();

        // update pid reference (we have a new daemon)
        $this->pid = $pid;

        // start process daemon
        $this->start();

    }
1253253
def _spawn_child(self,
	                 command,
	                 args=None,
	                 timeout=shutit_global.shutit_global_object.default_timeout,
	                 maxread=2000,
	                 searchwindowsize=None,
	                 env=None,
	                 ignore_sighup=False,
	                 echo=True,
	                 preexec_fn=None,
	                 encoding=None,
	                 codec_errors='strict',
	                 dimensions=None,
	                 delaybeforesend=shutit_global.shutit_global_object.delaybeforesend):
		
		shutit = self.shutit
		args = args or []
		pexpect_child = pexpect.spawn(command,
		                              args=args,
		                              timeout=timeout,
		                              maxread=maxread,
		                              searchwindowsize=searchwindowsize,
		                              env=env,
		                              ignore_sighup=ignore_sighup,
		                              echo=echo,
		                              preexec_fn=preexec_fn,
		                              encoding=encoding,
		                              codec_errors=codec_errors,
		                              dimensions=dimensions)
		# Set the winsize to the theoretical maximum to reduce risk of trouble from terminal line wraps.
		# Other things have been attempted, eg tput rmam/smam without success.
		pexpect_child.setwinsize(shutit_global.shutit_global_object.pexpect_window_size[0],shutit_global.shutit_global_object.pexpect_window_size[1])
		pexpect_child.delaybeforesend=delaybeforesend
		shutit.log('sessions before: ' + str(shutit.shutit_pexpect_sessions), level=logging.DEBUG)
		shutit.shutit_pexpect_sessions.update({self.pexpect_session_id:self})
		shutit.log('sessions after: ' + str(shutit.shutit_pexpect_sessions), level=logging.DEBUG)
		return pexpect_child