Fork a child process.
198926
def patched_fork(self):
        """"""
        pid = self.original_os_fork()
        if not pid:
            _LOG('Fork detected. Reinstalling Manhole.')
            self.reinstall()
        return pid
465388
public static function fork()
    {
        $pid = pcntl_fork();
        if ($pid === -1) {
            throw new \RuntimeException('Failed to fork PHP process');
        } elseif ($pid > 0) {
            // This is the parent process. If the child process succeeds, this
            // receives SIGCHLD. If it fails, this receives SIGTERM.
            declare (ticks = 1);
            pcntl_signal(SIGCHLD, function () {
                exit;
            });
            pcntl_signal(SIGTERM, function () {
                exit(1);
            });

            // Wait a reasonable amount of time for the child processes to
            // finish.
            sleep(60);
            throw new \RuntimeException('Timeout in parent process');
        } elseif (posix_setsid() === -1) {
            throw new \RuntimeException('Child process failed to become session leader');
        }
    }
1121426
def spawn(func, kwargs):
    """"""
    t = threading.Thread(target=func, kwargs=kwargs)
    t.start()
    yield
    t.join()
1296587
function tsc(projectPath, done) {
  const path = require('path');
  const platformScriptPath = require('./platform-script-path');
  const childProcess = require('child_process');

  childProcess
      .spawn(
          path.join(__dirname, platformScriptPath('../../node_modules/.bin/tsc')),
          ['-p', path.join(__dirname, '../..', projectPath)], {stdio: 'inherit'})
      .on('close', done);
}
525784
def run(self):
        '''

        '''
        setproctitle('rejester fork_worker for namespace {0}'
                     .format(self.config.get('namespace', None)))
        self.set_signal_handlers()
        try:
            self.start_log_child()
            while True:
                can_start_more = not self.shutting_down
                if time.time() >= self.heartbeat_deadline:
                    mode = self.heartbeat()
                    if mode != self.last_mode:
                        self.log(logging.INFO,
                                 'rejester global mode is {0!r}'.format(mode))
                        self.last_mode = mode
                    self.heartbeat_deadline = (time.time() +
                                               self.heartbeat_interval)
                    self.check_spinning_children()
                else:
                    mode = self.last_mode
                if mode != self.task_master.RUN:
                    can_start_more = False
                interval = self.do_some_work(can_start_more)
                # Normal shutdown case
                if len(self.children) == 0:
                    if mode == self.task_master.TERMINATE:
                        self.log(logging.INFO,
                                 'stopping for rejester global shutdown')
                        break
                    if self.shutting_down:
                        self.log(logging.INFO,
                                 'stopping in response to signal')
                        break
                time.sleep(interval)
        except Exception:
            self.log(logging.CRITICAL,
                     'uncaught exception in worker: ' + traceback.format_exc())
        finally:
            # See the note in run_workers() above.  clear_signal_handlers()
            # calls signal.signal() which explicitly affects the current
            # process, parent or child.
            self.clear_signal_handlers()
450458
public void execute(Fork fork) {
    LOG.info(String.format("Executing fork %d of task %s", fork.getIndex(), fork.getTaskId()));
    this.forkExecutor.execute(fork);
  }
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)
1246853
def child_watch_add(*args, **kwargs):
    """"""
    priority, pid, function, data = _child_watch_add_get_args(*args, **kwargs)
    return GLib.
529777
function fork$(parent$, mapFunction) {
  let initValue =
    parent$.value !== undefined ? mapFunction(parent$.value) : undefined;
  return stream(initValue);
}
1014315
def pre_fork(self, process_manager, kwargs=None):
        '''
        
        '''
        process_manager.add_process(self._publish_daemon, kwargs=kwargs)
1353920
def daemonize(self):
        """"""
        self._double_fork()

        # Write pidfile.
        self.pid = os.getpid()

        LOG.info(
            "Succesfully daemonized process {0}.".format(self.pid)
        )
578038
def run
      rd, wr = IO.pipe
      if fork
        # grandparent
        wr.close
        begin
          master_pid = rd.readpartial(16).to_i
          exit
        rescue EOFError
          puts "Master process failed to start!"
          exit! 1
        end
      elsif fork
        # parent
        Process.setsid
        exit
      else
        # master
        STDIN.reopen "/dev/null"
        STDOUT.reopen "/dev/null", "a"
        STDERR.reopen "/dev/null", "a"
        rd.close
        @master.run(wr)
      end
    end
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)
158593
def create_daemon():
    

    try:
        # Fork a child process so the parent can exit.  This returns control to
        # the command-line or shell.  It also guarantees that the child will not
        # be a process group leader, since the child receives a new process ID
        # and inherits the parent's process group ID.  This step is required
        # to insure that the next call to os.setsid is successful.
        pid = os.fork()
    except OSError as err:
        raise Exception("%s [%d]" % (err.strerror, err.errno))

    if pid == 0:  # The first child.
        # To become the session leader of this new session and the process group
        # leader of the new process group, we call os.setsid().  The process is
        # also guaranteed not to have a controlling terminal.
        os.setsid()

        # Is ignoring SIGHUP necessary?
        #
        # It's often suggested that the SIGHUP signal should be ignored before
        # the second fork to avoid premature termination of the process.  The
        # reason is that when the first child terminates, all processes, e.g.
        # the second child, in the orphaned group will be sent a SIGHUP.
        #
        # "However, as part of the session management system, there are exactly
        # two cases where SIGHUP is sent on the death of a process:
        #
        #   1) When the process that dies is the session leader of a session that
        #      is attached to a terminal device, SIGHUP is sent to all processes
        #      in the foreground process group of that terminal device.
        #   2) When the death of a process causes a process group to become
        #      orphaned, and one or more processes in the orphaned group are
        #      stopped, then SIGHUP and SIGCONT are sent to all members of the
        #      orphaned group." [2]
        #
        # The first case can be ignored since the child is guaranteed not to have
        # a controlling terminal.  The second case isn't so easy to dismiss.
        # The process group is orphaned when the first child terminates and
        # POSIX.1 requires that every STOPPED process in an orphaned process
        # group be sent a SIGHUP signal followed by a SIGCONT signal.  Since the
        # second child is not STOPPED though, we can safely forego ignoring the
        # SIGHUP signal.  In any case, there are no ill-effects if it is ignored.
        #
        # import signal           # Set handlers for asynchronous events.
        # signal.signal(signal.SIGHUP, signal.SIG_IGN)

        try:
            # Fork a second child and exit immediately to prevent zombies.  This
            # causes the second child process to be orphaned, making the init
            # process responsible for its cleanup.  And, since the first child is
            # a session leader without a controlling terminal, it's possible for
            # it to acquire one by opening a terminal in the future (System V-
            # based systems).  This second fork guarantees that the child is no
            # longer a session leader, preventing the daemon from ever acquiring
            # a controlling terminal.
            pid = os.fork()  # Fork a second child.
        except OSError as err:
            raise Exception("%s [%d]" % (err.strerror, err.errno))

        if pid == 0:  # The second child.
            # Since the current working directory may be a mounted filesystem, we
            # avoid the issue of not being able to unmount the filesystem at
            # shutdown time by changing it to the root directory.
            os.chdir(WORKDIR)
            # We probably don't want the file mode creation mask inherited from
            # the parent, so we give the child complete control over permissions.
            os.umask(UMASK)
        else:
            # exit() or _exit()?  See below.
            _exit(0)  # Exit parent (the first child) of the second child.
    else:
        # exit() or _exit()?
        # _exit is like exit(), but it doesn't call any functions registered
        # with atexit (and on_exit) or any registered signal handlers.  It also
        # closes any open file descriptors.  Using exit() may cause all stdio
        # streams to be flushed twice and any temporary files may be unexpectedly
        # removed.  It's therefore recommended that child branches of a fork()
        # and the parent branch(es) of a daemon use _exit().
        _exit(0)  # Exit parent of the first child.

    # Close all open file descriptors.  This prevents the child from keeping
    # open any file descriptors inherited from the parent.  There is a variety
    # of methods to accomplish this task.  Three are listed below.
    #
    # Try the system configuration variable, SC_OPEN_MAX, to obtain the maximum
    # number of open file descriptors to close.  If it doesn't exists, use
    # the default value (configurable).
    #
    # try:
    #    maxfd = os.sysconf("SC_OPEN_MAX")
    # except (AttributeError, ValueError):
    #    maxfd = MAXFD
    #
    # OR
    #
    # if os.sysconf_names.has_key("SC_OPEN_MAX"):
    #    maxfd = os.sysconf("SC_OPEN_MAX")
    # else:
    #    maxfd = MAXFD
    #
    # OR
    #
    # Use the getrlimit method to retrieve the maximum file descriptor number
    # that can be opened by this process.  If there is not limit on the
    # resource, use the default value.
    #
    import resource  # Resource usage information.
    maxfd = resource.getrlimit(resource.RLIMIT_NOFILE)[1]
    if maxfd == resource.RLIM_INFINITY:
        maxfd = MAXFD

    # Iterate through and close all file descriptors.
    for file_desc in range(0, maxfd):
        try:
            os.close(file_desc)
        except OSError:  # file descriptor wasn't open to begin with (ignored)
            pass

    # Redirect the standard I/O file descriptors to the specified file.  Since
    # the daemon has no controlling terminal, most daemons redirect stdin,
    # stdout, and stderr to /dev/null.  This is done to prevent side-effects
    # from reads and writes to the standard I/O file descriptors.

    # This call to open is guaranteed to return the lowest file descriptor,
    # which will be 0 (stdin), since it was closed above.
    os.open(REDIRECT_TO, os.O_RDWR)  # standard input (0)

    # Duplicate standard input to standard output and standard error.
    os.dup2(0, 1)  # standard output (1)
    os.dup2(0, 2)  # standard error (2)

    return 0
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)
282489
function ChildBench(name, file, opts){
  opts || (opts = {})
  var args = [file]
  var options = {}
  // extra process arguments
  if (opts.args) args.push.apply(args, opts.args)
  // bench subject
  if (opts.subject) options.env = { subject: opts.subject }
  var reqs = this.requests = {}

  this.child = fork(runner, args, options)
    .on('message', function(msg){
      var result = reqs[msg.id]
      msg.value.name = name
      switch (msg.type) {
        case 'result': result.write(msg.value); break
        case 'error':
          var err = new Error(msg.value.message)
          err.stack = msg.value.stack
          result.error(err)
          break
        default:
          throw new Error('unknown message ' + JSON.stringify(msg))
      }
    })
    // clean up
    .on('exit', function(code){
      if (code > 0) process.exit(code)
    })
}
1363188
def server_main(loop, path):
    """"""
    loop.fork()
    logger.debug('forked function')
    sigintwatcher = pyev.Signal(signal.SIGINT, loop, lambda watcher, events: logger.info('interrupt ignored'))
    sigintwatcher.start()
    sigtermwatcher = pyev.Signal(signal.SIGTERM, loop, server_stop)
    sigtermwatcher.start()
    adder = AdderService()
    dispatcher = ObjectDispatch(adder)
    pickle_factory = PickleProtocolFactory(dispatcher)
    pickle_server = UnixServer(loop, pickle_factory, path)
    pickle_server.start()
    msgpack_factory = MsgPackProtocolFactory(dispatcher)
    msgpack_server = UnixServer(loop, msgpack_factory, path + '_mp')
    msgpack_server.start()

    logger.debug('running server loop')

    import cProfile
    cProfile.runctx('loop.loop()', None, {'loop':loop}, 'server_profile')

    logger.debug('server unlooped')