Do the UNIX double-fork magic.

        See Stevens' "Advanced Programming in the UNIX Environment" for details
        (ISBN 0201563177)
        http://www.erlenstar.demon.co.uk/unix/faq_2.html#SEC16
352412
def _double_fork(self):
        
        try:

            pid = os.fork()
            if pid > 0:

                # Exit first parent.
                sys.exit(0)
                return None

        except OSError as err:

            LOG.exception(
                "Fork #1 failed: {0} ({1})".format(
                    err.errno,
                    err.strerror,
                ),
            )
            sys.exit(exit.DAEMONIZE_FAILED)
            return None

        # 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.
                sys.exit(0)

        except OSError as err:

            LOG.exception(
                "Fork #2 failed: {0} ({1})".format(
                    err.errno,
                    err.strerror,
                ),
            )
            sys.exit(exit.DAEMONIZE_FAILED)
            return None
545199
def call(*, **, &block)
      pid = fork_and_return_pid(&block)
      write.close
      result = read.read
      Process.wait(pid)

      # rubocop:disable MarshalLoad
      Marshal.load(result)
      # rubocop:enable MarshalLoad
    end
453268
function forkProc(cwd, cmd, args, cb) {
    var env = process.env
    if (typeof(cwd) === 'object') {
      cb = cmd
      var cmd = cwd.cmd
      var args = cwd.args
      // Merge/override any variables
      mergeObj(cwd.env, env)
      cwd = cwd.cwd
    }
    if (typeof(cmd) === 'string' && typeof(args) === 'function') {
      var split = cmd.split(/\s+/)
      cmd = split[0]
      cb = args
      args = split.slice(1)
    }
    var proc = spawn(cmd, args, {cwd: cwd, env: env})

    // per-process output buffers
    proc.stderrBuffer = ""
    proc.stdoutBuffer = ""
    proc.stdmergedBuffer = ""

    proc.stdout.setEncoding('utf8')
    proc.stderr.setEncoding('utf8')

    proc.stdout.on('data', function(buf) {
      proc.stdoutBuffer += buf
      proc.stdmergedBuffer += buf
      stdoutBuffer += buf
      stdmergedBuffer += buf
      updateStatus("deployUpdate" , {stdout:buf})
    })

    proc.stderr.on('data', function(buf) {
      proc.stderrBuffer += buf
      proc.stdmergedBuffer += buf
      stderrBuffer += buf
      stdmergedBuffer += buf
      updateStatus("deployUpdate", {stderr:buf})
    })

    proc.on('close', function(exitCode) {
      cb(exitCode)
    })

    return proc
  }
1138326
function fork(number) {
  var numProc = number || require('os').cpus().length;

  config.n = numProc;

  debug('forking %d workers', numProc);

  forkLoopProtect();

  for (var i = 0; i < numProc; i++) {
    cluster.fork({PWD: config.CWD});
  }
}
1282804
function branch(inst, list, argv, event, fin) {
    if (argv.length > 0) {
        // Append the argv for programs that return
        // a list that accepts them as parameters
        list = list.concat(argv.splice(0));
    }
    // HACK HACK HACK. OK, so, when dealing with deeply recursive
    // functions in Runiq, we may hit an error where we exceed the
    // available call stack size. A setTimeout will get us a fresh
    // call stack, but at serious perf expense, since setTimeouts
    // end up triggered 4 ms later. So what I'm doing here is
    // trying to call unload, and if that gives an error, then
    // falling back to setTimeout method. This technique has an
    // incredible benefit, speeding up Runiq programs by 50X or so.
    // However, it could prove unworkable depending on browser support
    // for catching call-stack errors.
    try {
        return unload(inst, list, argv, event, fin);
    }
    catch (e) {
        return setTimeout(function branchCallback() {
            Console.printWarning(inst, "Caught call stack error: " + e);
            return unload(inst, list, argv, event, fin);
        }, 0);
    }
}
219162
def _modf(ins):
    ''' 
    '''
    op1, op2 = tuple(ins.quad[2:])
    output = _float_oper(op1, op2)
    output.append('call __MODF')
    output.extend(_fpush())
    REQUIRES.add('modf.asm')
    return output
905013
function exec(inst, raw, argv, event, fin) {
    var after = nextup(inst, raw, argv, event, fin);
    return step(inst, raw, argv, event, passthrough(after));
}
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();
                }
            });
        }
854248
def create_warn_fork_exec(original_name):
    

    def new_warn_fork_exec(*args):
        try:
            import _posixsubprocess
            warn_multiproc()
            return getattr(_posixsubprocess, original_name)(*args)
        except:
            pass

    return new_warn_fork_exec
723469
def fork(object)
      Query.new(object, source: @sources, protocol: @protocols).tap {|q|
        q.parent = self
      }.tap {|c| self.add_child c }
    end
262280
def daemonize(pidfile=None, logfile=None, sync=True):
    
    log = logging.getLogger("daemonize")
    ppid = os.getpid()

    try:
        pid = os.fork()
        if pid > 0:
            log.debug("Parent exiting (PID %d, CHILD %d)" % (ppid, pid))
            sys.exit(0)
    except OSError as exc:
        log.critical("fork #1 failed (PID %d): (%d) %s\n" % (os.getpid(), exc.errno, exc.strerror))
        sys.exit(1)

    ##os.chdir("/")
    ##os.umask(0022)
    os.setsid()

    try:
        pid = os.fork()
        if pid > 0:
            log.debug("Session leader exiting (PID %d, PPID %d, DEMON %d)" % (os.getpid(), ppid, pid))
            sys.exit(0)
    except OSError as exc:
        log.critical("fork #2 failed (PID %d): (%d) %s\n" % (os.getpid(), exc.errno, exc.strerror))
        sys.exit(1)

    if pidfile:
        _write_pidfile(pidfile)

    def sig_term(*dummy):
        "Handler for SIGTERM."
        sys.exit(0)

    stdin = open("/dev/null", "r")
    os.dup2(stdin.fileno(), sys.stdin.fileno())
    signal.signal(signal.SIGTERM, sig_term)

    if logfile:
        try:
            logfile + ""
        except TypeError:
            if logfile.fileno() != sys.stdout.fileno():
                os.dup2(logfile.fileno(), sys.stdout.fileno())
            if logfile.fileno() != sys.stderr.fileno():
                os.dup2(logfile.fileno(), sys.stderr.fileno())
        else:
            log.debug("Redirecting stdout / stderr to %r" % logfile)
            loghandle = open(logfile, "a+")
            os.dup2(loghandle.fileno(), sys.stdout.fileno())
            os.dup2(loghandle.fileno(), sys.stderr.fileno())
            loghandle.close()

    if sync:
        # Wait for 5 seconds at most, in 10ms steps
        polling = 5, .01
        for _ in range(int(polling[0] * 1 / polling[1])):
            try:
                os.kill(ppid, 0)
            except OSError:
                break
            else:
                time.sleep(polling[1])

    log.debug("Process detached (PID %d)" % os.getpid())
845792
def daemonize(logfile):
    
    
    # turn off GC across the fork
    gc.collect(2)
    gc.collect(1)
    gc.collect(0)
    gc.disable()
    
    child_pid = os.fork()

    if child_pid == 0:
        # child!
        sys.stdin.close()
        os.dup2(logfile.fileno(), sys.stdout.fileno())
        os.dup2(logfile.fileno(), sys.stderr.fileno())

        soft_num_open_files, hard_num_open_files = resource.getrlimit(resource.RLIMIT_NOFILE)
        if hard_num_open_files == resource.RLIM_INFINITY:
            # guess
            hard_num_open_files = 1024

        # we don't have many other fds open yet
        for i in range(3, hard_num_open_files):
            if i == logfile.fileno():
                continue

            try:
                os.close(i)
            except:
                pass

        os.setsid()

        daemon_pid = os.fork()
        if daemon_pid == 0:
            # daemon! chdir and return
            os.chdir('/')
            gc.enable()
            gc.collect(2)
            gc.collect(1)
            gc.collect(0)
            return 0

        elif daemon_pid > 0:
            # parent (intermediate child)
            sys.exit(0)

        else:
            # error
            sys.exit(1)

    elif child_pid > 0:
        # grand-parent (caller)
        # re-activate gc
        gc.enable()
        gc.collect(2)
        gc.collect(1)
        gc.collect(0)

        # wait for intermediate child.
        # panic if we don't hear back after 5 minutes
        timeout = 600
        if BLOCKSTACK_TEST:
            # wait around so we can attach gdb or whatever
            timeout = 60000

        for i in range(0, timeout):
            pid, status = os.waitpid(child_pid, os.WNOHANG)
            if pid == 0:
                # still waiting
                time.sleep(1)
                log.debug("Still waiting on {}".format(child_pid))
                continue

            # child has exited!
            if os.WEXITSTATUS(status) == 0:
                return child_pid
            else:
                log.error("Child exit status {}".format(status))
                return -1

        # child has not exited yet.  This is not okay.
        log.error("Child PID={} did not exit.  Killing it instead and failing...".format(child_pid))
        os.kill(child_pid, signal.SIGKILL)
        return -1
    
    else:
        # failed to fork 
        log.error("Failed to fork")
        return -1

    # parent! success
    return child_pid
140856
def spawn_daemon(fork=None, pgrpfile=None, outfile='out.txt'):
    ''
    global LAST_PGRP_PATH
    fork = fork or os.fork
    open(outfile, 'a').close()  # TODO: configurable output file
    if pgrpfile and os.path.exists(pgrpfile):
        try:
            cur_pid = int(open(pgrpfile).read().rstrip("\n"))
            os.killpg(cur_pid, 0)
            raise Exception("arbiter still running with pid:" + str(cur_pid))
        except (OSError, ValueError):
            pass
    if fork():  # return True means we are in parent
        return True
    else:
        os.setsid()  # break association with terminal via new session id
        if fork():  # fork one more layer to ensure child will not re-acquire terminal
            os._exit(0)
        LAST_PGRP_PATH = pgrpfile
        if pgrpfile:
            with open(pgrpfile, 'w') as f:
                f.write(str(os.getpgrp()) + "\n")
        logging.root.addHandler(SysLogHandler())
        rotating_out = RotatingStdoutFile(outfile)
        rotating_out.start()
        return False
799884
def daemonize(enable_stdio_inheritance=False,
              auto_close_fds=True,
              keep_fds=None):   # pragma    nocover
    
    if os.fork():
        os._exit(0)
    os.setsid()

    if os.fork():
        os._exit(0)

    os.umask(0o22)

    # In both the following any file descriptors above stdin
    # stdout and stderr are left untouched. The inheritence
    # option simply allows one to have output go to a file
    # specified by way of shell redirection when not wanting
    # to use --error-log option.

    if not enable_stdio_inheritance:
        # Remap all of stdin, stdout and stderr on to
        # /dev/null. The expectation is that users have
        # specified the --error-log option.

        if keep_fds:
            keep_fds = set(keep_fds)
            for fd in range(0, 3):
                if fd not in keep_fds:
                    try:
                        os.close(fd)
                    except OSError:
                        pass
        else:
            os.closerange(0, 3)

        fd_null = os.open(REDIRECT_TO, os.O_RDWR)

        if fd_null != 0:
            os.dup2(fd_null, 0)

        os.dup2(fd_null, 1)
        os.dup2(fd_null, 2)

    else:
        fd_null = os.open(REDIRECT_TO, os.O_RDWR)

        # Always redirect stdin to /dev/null as we would
        # never expect to need to read interactive input.

        if fd_null != 0:
            os.close(0)
            os.dup2(fd_null, 0)

        # If stdout and stderr are still connected to
        # their original file descriptors we check to see
        # if they are associated with terminal devices.
        # When they are we map them to /dev/null so that
        # are still detached from any controlling terminal
        # properly. If not we preserve them as they are.
        #
        # If stdin and stdout were not hooked up to the
        # original file descriptors, then all bets are
        # off and all we can really do is leave them as
        # they were.
        #
        # This will allow 'gunicorn ... > output.log 2>&1'
        # to work with stdout/stderr going to the file
        # as expected.
        #
        # Note that if using --error-log option, the log
        # file specified through shell redirection will
        # only be used up until the log file specified
        # by the option takes over. As it replaces stdout
        # and stderr at the file descriptor level, then
        # anything using stdout or stderr, including having
        # cached a reference to them, will still work.

        def redirect(stream, fd_expect):
            try:
                fd = stream.fileno()
                if fd == fd_expect and stream.isatty():
                    os.close(fd)
                    os.dup2(fd_null, fd)
            except AttributeError:
                pass

        redirect(sys.stdout, 1)
        redirect(sys.stderr, 2)
606716
def create_fork(self):
        
        headers, data = self._requester.requestJsonAndCheck(
            "POST",
            self.url + "/forks"
        )
        return Gist(self._requester, headers, data, completed=True)
457460
def daemonize(self):
        
        try:
            pid = os.fork()
            if pid > 0:
                # exit first parent
                sys.exit(0)
        except OSError as e:
            self.logger.error("Fork #1 failed: %d (%s)\n" % (e.errno, e.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
                sys.exit(0)
        except OSError as e:
            self.logger.error("Fork #2 failed: %d (%s)\n" % (e.errno, e.strerror))
            sys.exit(1)

        # write pidfile
        atexit.register(self.delpid)
        pid = str(os.getpid())
        with open(self.pidfile,'w+') as f:
            f.write("%s\n" % pid)

        sys.stdout = LoggerProxy(self.logger.info)
        sys.stderr = LoggerProxy(self.logger.error)
63899
def pre_fork(self, process_manager):
        '''
        
        '''
        salt.transport.mixins.auth.AESReqServerMixin.pre_fork(self, process_manager)
        process_manager.add_process(self.zmq_device)