Post-fork child process callback executed via ProcessManager.daemonize().
552190
def post_fork_child(self):
    """"""
    # Set the Exiter exception hook post-fork so as not to affect the pantsd processes exception
    # hook with socket-specific behavior. Note that this intentionally points the faulthandler
    # trace stream to sys.stderr, which at this point is still a _LoggerStream object writing to
    # the `pantsd.log`. This ensures that in the event of e.g. a hung but detached pantsd-runner
    # process that the stacktrace output lands deterministically in a known place vs to a stray
    # terminal window.
    # TODO: test the above!
    ExceptionSink.reset_exiter(self._exiter)

    ExceptionSink.reset_interactive_output_stream(sys.stderr.buffer if PY3 else sys.stderr)
    ExceptionSink.reset_signal_handler(DaemonSignalHandler())

    # Ensure anything referencing sys.argv inherits the Pailgun'd args.
    sys.argv = self._args

    # Set context in the process title.
    set_process_title('pantsd-runner [{}]'.format(' '.join(self._args)))

    # Broadcast our process group ID (in PID form - i.e. negated) to the remote client so
    # they can send signals (e.g. SIGINT) to all processes in the runners process group.
    NailgunProtocol.send_pid(self._socket, os.getpid())
    NailgunProtocol.send_pgrp(self._socket, os.getpgrp() * -1)

    # Stop the services that were paused pre-fork.
    for service in self._services.services:
      service.terminate()

    # Invoke a Pants run with stdio redirected and a proxied environment.
    with self.nailgunned_stdio(self._socket, self._env) as finalizer,\
         hermetic_environment_as(**self._env):
      try:
        # Setup the Exiter's finalizer.
        self._exiter.set_finalizer(finalizer)

        # Clean global state.
        clean_global_runtime_state(reset_subsystem=True)

        # Otherwise, conduct a normal run.
        runner = LocalPantsRunner.create(
          self._exiter,
          self._args,
          self._env,
          self._target_roots,
          self._graph_helper,
          self._options_bootstrapper
        )
        runner.set_start_time(self._maybe_get_client_start_time_from_env(self._env))

        # Re-raise any deferred exceptions, if present.
        self._raise_deferred_exc()

        runner.run()
      except KeyboardInterrupt:
        self._exiter.exit_and_fail('Interrupted by user.\n')
      except _GracefulTerminationException as e:
        ExceptionSink.log_exception(
          'Encountered graceful termination exception {}; exiting'.format(e))
        self._exiter.exit(e.exit_code)
      except Exception:
        # TODO: We override sys.excepthook above when we call ExceptionSink.set_exiter(). That
        # excepthook catches `SignalHandledNonLocalExit`s from signal handlers, which isn't
        # happening here, so something is probably overriding the excepthook. By catching Exception
        # and calling this method, we emulate the normal, expected sys.excepthook override.
        ExceptionSink._log_unhandled_exception_and_exit()
      else:
        self._exiter.exit(PANTS_SUCCEEDED_EXIT_CODE)
1008941
def _fork_and_supervise_child(cls):
        """"""
        pid = os.fork()
        if pid == 0:
            # Fork again but orphan the child this time so we'll have
            # the original parent and the second child which is orphaned
            # so we don't have to worry about it becoming a zombie
            cls._orphan_this_process()
            return
        # Since this process is not going to exit, we need to call
        # os.waitpid() so that the first child doesn't become a zombie
        os.waitpid(pid, 0)

        # Generate a list of PIDs to exclude when checking for processes
        # in the group (exclude all ancestors that are in the group)
        pgid = os.getpgrp()
        exclude_pids = set([0, os.getpid()])
        proc = psutil.Process()
        while os.getpgid(proc.pid) == pgid:
            exclude_pids.add(proc.pid)
            proc = psutil.Process(proc.ppid())

        while True:
            try:
                # Look for other processes in this process group
                group_procs = []
                for proc in psutil.process_iter():
                    try:
                        if (os.getpgid(proc.pid) == pgid and
                                proc.pid not in exclude_pids):
                            # We found a process in this process group
                            group_procs.append(proc)
                    except (psutil.NoSuchProcess, OSError):
                        continue

                if group_procs:
                    psutil.wait_procs(group_procs, timeout=1)
                else:
                    # No processes were found in this process group
                    # so we can exit
                    cls._emit_message(
                        'All children are gone. Parent is exiting...\n')
                    sys.exit(0)
            except KeyboardInterrupt:
                # Don't exit immediatedly on Ctrl-C, because we want to
                # wait for the child processes to finish
                cls._emit_message('\n')
                continue
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'])))
1345537
function(params){
		process.nextTick(function(){
			var strippedName = params.name.replace(/-/g, "");
			if(!params.name){
				log("startup", "Name not passed correctly to daemon module");
				process.exit();
			}
			daemon = daemonize.setup({
	    		main: "../../server.js",
	    		name: strippedName,
	    		pidfile: "/var/run/" + strippedName + ".pid",
	    		cwd: process.cwd(),
	    		silent: true
			});
			if(process.argv[0].endsWith("sudo") && process.argv[1].endsWith("node")) { var i = 3 }
			else if (process.argv[0].endsWith("sudo") && !process.argv[1].endsWith("node")) { var i = 2 }
			else if (process.argv[0].endsWith("node")) { var i = 2 }
			else { var i = 1 }
			if((((process.argv[i] == "start" && process.argv[i+1] == "daemon") || (process.argv[i] == "start" && !process.argv[i+1]) || (config.cli && config.cli.mode && config.cli.mode == "daemon")) || ((process.argv[i] == "stop" && process.argv[i+1] == "daemon") || (process.argv[i] == "stop" && !process.argv[i+1]))) && !params.isChildProcess){
				if (process.getuid() != 0) {
				    log("startup", "Daemon is expected to run as root");
				    process.exit();
				    return false;
				}
				daemon
				    .on("starting", function() {
				        log("startup", "Starting daemon...");
				    })
				    .on("started", function(pid) {
				        log("startup", "Daemon started. PID: " + pid);
				        process.exit();
				    })
				    .on("stopping", function() {
				        log("startup", "Stopping daemon...");
				    })
				    .on("stopped", function(pid) {
				        log("startup", "Daemon stopped.");
				        process.exit();
				    })
				    .on("running", function(pid) {
				        log("startup", "Daemon already running. PID: " + pid);
				        process.exit();
				    })
				    .on("notrunning", function() {
				        log("startup", "Daemon is not running");
				        process.exit();
				    })
				    .on("error", function(err) {
				        log("startup", "Daemon failed to start:  " + err.message);
				        process.exit();
				    });
				if ((process.argv[i] == "start" && process.argv[i+1] == "daemon") || (process.argv[i] == "start" && !process.argv[i+1]) || (config.cli && config.cli.mode && config.cli.mode == "daemon" && !daemon.status())) {
					daemon.start();
				} else if ((process.argv[i] == "stop" && process.argv[i+1] == "daemon") || (process.argv[i] == "stop" && !process.argv[i+1]) || (config.cli && config.cli.mode && config.cli.mode == "daemon" && daemon.status())) {
					daemon.stop();
				}
				return true;
			} else if ((process.argv[i] == "status" && process.argv[i+1] == "daemon") || (process.argv[i] == "status" && !process.argv[i+1])) {
				var status = daemon.status();
				if(status){
					log("startup", "Daemon is running.");
					process.exit();
				} else {
					log("startup", "Daemon is not running.");
					process.exit();
				}
				return true;
			} else if (((process.argv[i] == "restart" && process.argv[i+1] == "daemon") || (process.argv[i] == "restart" && !process.argv[i+1]))  && !params.isChildProcess) {
				if (process.getuid() != 0) {
				    log("startup", "Daemon is expected to run as root");
				    process.exit();
				    return false;
				}
				var status = daemon.status();
				if(status){
					daemon
					    .on("starting", function() {
					        log("startup", "Starting daemon...");
					    })
					    .on("started", function(pid) {
					        log("startup", "Daemon started. PID: " + pid);
					        process.exit();
					    })
					    .on("stopping", function() {
					        log("startup", "Stopping daemon...");
					    })
					    .on("stopped", function(pid) {
					        log("startup", "Daemon stopped.");
					        process.exit();
					        daemon.start();
					    })
					    .on("running", function(pid) {
					        log("startup", "Daemon already running. PID: " + pid);
					        process.exit();
					    })
					    .on("notrunning", function() {
					        log("startup", "Daemon is not running");
					        process.exit();
					    })
					    .on("error", function(err) {
					        log("startup", "Daemon failed to start:  " + err.message);
					        process.exit();
					    });
					    daemon.stop();
				} else {
					log("fatal", "Daemon is not running. Use start command instead.");
					process.exit();
				}
			} else {
				log("fatal", "Daemon received invalid command. Terminating application.");
				process.exit();
				return false;
			}
		});		
	}
579198
public void postProcess(DirContext ctx) throws NamingException {
        for (DirContextProcessor processor : dirContextProcessors) {
            processor.postProcess(ctx);
        }
    }
192795
def daemonize(redirect_out=True):
    '''
    
    '''
    # Avoid circular import
    import salt.utils.crypt
    try:
        pid = os.fork()
        if pid > 0:
            # exit first parent
            salt.utils.crypt.reinit_crypto()
            os._exit(salt.defaults.exitcodes.EX_OK)
    except OSError as exc:
        log.error('fork #1 failed: %s (%s)', exc.errno, exc)
        sys.exit(salt.defaults.exitcodes.EX_GENERIC)

    # decouple from parent environment
    os.chdir('/')
    # noinspection PyArgumentList
    os.setsid()
    os.umask(0o022)  # pylint: disable=blacklisted-function

    # do second fork
    try:
        pid = os.fork()
        if pid > 0:
            salt.utils.crypt.reinit_crypto()
            sys.exit(salt.defaults.exitcodes.EX_OK)
    except OSError as exc:
        log.error('fork #2 failed: %s (%s)', exc.errno, exc)
        sys.exit(salt.defaults.exitcodes.EX_GENERIC)

    salt.utils.crypt.reinit_crypto()

    # A normal daemonization redirects the process output to /dev/null.
    # Unfortunately when a python multiprocess is called the output is
    # not cleanly redirected and the parent process dies when the
    # multiprocessing process attempts to access stdout or err.
    if redirect_out:
        with salt.utils.files.fopen('/dev/null', 'r+') as dev_null:
            # Redirect python stdin/out/err
            # and the os stdin/out/err which can be different
            os.dup2(dev_null.fileno(), sys.stdin.fileno())
            os.dup2(dev_null.fileno(), sys.stdout.fileno())
            os.dup2(dev_null.fileno(), sys.stderr.fileno())
            os.dup2(dev_null.fileno(), 0)
            os.dup2(dev_null.fileno(), 1)
            os.dup2(dev_null.fileno(), 2)
198730
def __postCallAction(self, event):
        
        aThread = event.get_thread()
        retval  = self._get_return_value(aThread)
        self.__callHandler(self.__postCB, event, retval)
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();

    }
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;
    }
945851
private function handleProcessExitStatus($PID, $child_type, $exitStatus) {
        $child_type = $child_type === self::PROCESS_TYPE_JOB ? "child" : "watchdog";

        if ($exitStatus === 0) {
            $this->logger->debug("{type}: {$child_type} process exited successfully", $this->logContext);

            return false;
        }

        $jobFailedMessage = $this->readErrorFromSocket($this->sockets[$PID]) ?: "{$child_type} process failed with status: {$exitStatus}";
        $this->logger->error("{type}: fatal error in {$child_type} process: {$jobFailedMessage}", $this->logContext);

        return $jobFailedMessage;
    }
73758
def daemonize_posix(self):
        
        logger.info('daemonize_posix')
        try:
            pid = os.fork()
            if pid > 0:
                logger.debug('forked first child, pid = %d' % (pid,))
                return pid
            logger.debug('in child after first fork, pid = %d' % (pid, ))
        except OSError as error:
            logger.exception('fork #1')
            sys.stderr.write("fork #1 failed: %d (%s)\n" % (error.errno, error.strerror))
            sys.exit(1)

        # decouple from parent environment
        os.chdir("/")
        os.setsid()
        os.umask(0)

        # do second fork
        try:
            pid = os.fork()
            if pid > 0:
                # exit from second parent
                logger.debug('forked second child, pid = %d, exiting' % (pid,))
                sys.exit(0)
        except OSError as error:
            logger.exception('fork #2')
            sys.stderr.write("fork #2 failed: %d (%s)\n" % (error.errno, error.strerror))
            sys.exit(1)

        # redirect standard file descriptors
        logger.info('daemonized, pid = %d' % (pid, ))
        sys.stdin.flush()
        sys.stdout.flush()
        sys.stderr.flush()

        os.dup2(self.stdin.fileno(), sys.stdin.fileno())
        os.dup2(self.stdout.fileno(), sys.stdout.fileno())
        os.dup2(self.stderr.fileno(), sys.stderr.fileno())

        # write pidfile
        atexit.register(self.delpid)
        pid = str(os.getpid())
        with open(self.pidfile, 'w+') as fd:
            fd.write("%s\n" % pid)
482829
def daemonize!
      if JRUBY
        # It's not a true daemon but when executed with & works like one
        thread = Thread.new {daemon_execute}
        thread.join

      elsif RUBY_VERSION < "1.9"
        logger.debug "Parent Process: #{Process.pid}"
        exit!(0) if fork
        logger.debug "Child Process: #{Process.pid}"
        daemon_execute

      else
        Process.daemon(true, true)
        daemon_execute
      end
    end
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
51511
def _daemonize(self):
        
        try:
            pid = os.fork()
            if pid > 0:
                sys.exit(0)
        except OSError, e:
            sys.stderr.write("fork #1 failed: %d (%s)\n" %
                             (e.errno, e.strerror))
            sys.exit(1)

        os.setsid()
        os.chdir("/")
        os.umask(0)

        try:
            pid = os.fork()
            if pid > 0:
                sys.exit(0)
        except OSError, e:
            sys.stderr.write("fork #2 failed: %d (%s)\n" %
                             (e.errno, e.strerror))
            sys.exit(1)

        sys.stdout.flush()
        sys.stderr.flush()
        if self.stdin:
            si = file(self.stdin, 'r')
            os.dup2(si.fileno(), sys.stdin.fileno())
        if self.stdout:
            so = file(self.stdout, 'a+')
            os.dup2(so.fileno(), sys.stdout.fileno())
        if self.stderr:
            se = file(self.stderr, 'a+', 0)
            os.dup2(se.fileno(), sys.stderr.fileno())
        atexit.register(self.delpid)
        pid = str(os.getpid())
        file(self.pidfile, 'w+').write("%s\n" % pid)
589856
def _function_handler(function, args, kwargs, pipe):
    """"""
    signal.signal(signal.SIGINT, signal.SIG_IGN)

    result = process_execute(function, *args, **kwargs)

    send_result(pipe, result)
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)
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')