Fork handling, blocking process.
165640
protected function main(): void
    {
        $this->logger->info('start job listener', [
            'category' => get_class($this),
        ]);

        $cursor_jobs = $this->jobs->getCursor([
            '$or' => [
                ['status' => JobInterface::STATUS_WAITING],
                ['status' => JobInterface::STATUS_POSTPONED],
            ],
        ]);

        $cursor_events = $this->events->getCursor([
            'timestamp' => ['$gte' => new UTCDateTime()],
            'job' => ['$exists' => true],
            'status' => ['$gt' => JobInterface::STATUS_POSTPONED],
        ]);

        $this->catchSignal();

        while ($this->loop()) {
            while ($this->loop()) {
                if (null === $cursor_events->current()) {
                    if ($cursor_events->getInnerIterator()->isDead()) {
                        $this->logger->error('event queue cursor is dead, is it a capped collection?', [
                            'category' => get_class($this),
                        ]);

                        $this->events->create();

                        $this->main();

                        break;
                    }

                    $this->events->next($cursor_events, function () {
                        $this->main();
                    });
                }

                $event = $cursor_events->current();
                $this->events->next($cursor_events, function () {
                    $this->main();
                });

                if($event === null) {
                    break;
                }

                $this->handleEvent($event);
            }

            if (null === $cursor_jobs->current()) {
                if ($cursor_jobs->getInnerIterator()->isDead()) {
                    $this->logger->error('job queue cursor is dead, is it a capped collection?', [
                        'category' => get_class($this),
                    ]);

                    $this->jobs->create();
                    $this->main();

                    break;
                }

                $this->jobs->next($cursor_jobs, function () {
                    $this->main();
                });

                continue;
            }

            $job = $cursor_jobs->current();

            $this->jobs->next($cursor_jobs, function () {
                $this->main();
            });

            $this->handleJob($job);
        }
    }
652950
public static void setBlocking(FileDescriptor fd, boolean blocking) throws IOException {
        try {
            int flags = Libcore.os.fcntlVoid(fd, F_GETFL);
            if (!blocking) {
                flags |= O_NONBLOCK;
            } else {
                flags &= ~O_NONBLOCK;
            }
            Libcore.os.fcntlLong(fd, F_SETFL, flags);
        } catch (ErrnoException errnoException) {
            throw errnoException.rethrowAsIOException();
        }
    }
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()
995512
def stop(self, timeout=None):
        

        self.stopping = True

        for process in list(self.processes):
            self.stop_process(process, timeout=timeout)
451820
def daemonize(self) -> None:
        """"""
        if os.fork() == 0:
            pid = os.fork()
            if pid == 0:
                try:
                    # Closing the sys.stdout and stderr file descriptors here causes
                    # the program to crash when attempting to log.
                    os.close(sys.stdout.fileno())
                    os.close(sys.stderr.fileno())
                    self._run()
                    sys.exit(0)
                except Exception as exception:
                    LOG.info("Not running %s due to %s", self._name, str(exception))
                    sys.exit(1)
            else:
                sys.exit(0)
945252
async function kill(pid) {
  try {
    process.kill(pid, 'SIGTERM')
  } catch (err) {
    if (err.code !== 'ESRCH') throw err
  }
}
459471
def handle(self):
        
        pid, fd = pty.fork()
        if pid:
            protocol = TelnetServerProtocolHandler(self.request, fd)
            protocol.handle()
        else:
            self.execute()
1261102
def fork():
    """"""

    try:
        pid, fd = os.forkpty()
    except (AttributeError, OSError):
        pass
    else:
        if pid == CHILD:
            try:
                os.setsid()
            except OSError:
                # os.forkpty() already set us session leader
                pass
        return pid, fd

    master_fd, slave_fd = openpty()
    pid = os.fork()
    if pid == CHILD:
        # Establish a new session.
        os.setsid()
        os.close(master_fd)

        # Slave becomes stdin/stdout/stderr of child.
        os.dup2(slave_fd, STDIN_FILENO)
        os.dup2(slave_fd, STDOUT_FILENO)
        os.dup2(slave_fd, STDERR_FILENO)
        if (slave_fd > STDERR_FILENO):
            os.close (slave_fd)

        # Explicitly open the tty to make it become a controlling tty.
        tmp_fd = os.open(os.ttyname(STDOUT_FILENO), os.O_RDWR)
        os.close(tmp_fd)
    else:
        os.close(slave_fd)

    # Parent and child process.
    return pid, master_fd
1344247
def shutdown!
      shutdown
      if term_child
        if fork_per_job?
          new_kill_child
        else
          # Raise TermException in the same process
          trap('TERM') do
            # ignore subsequent terms
          end
          raise TermException.new("SIGTERM")
        end
      else
        kill_child
      end
    end
1330292
function forkTimeoutHandler(worker, cluster) {
    verbose('worker %d is stuck in fork', worker.process.pid);

    if (!cluster.workers[worker.id]) {
      return;
    }

    // something is wrong with this worker.  Kill it!
    master.suicideOverrides[worker.id] = worker.id;

    master.isRunning(worker, function(running) {
      if (!running) {
        return;
      }

      try {
        debug('sending SIGKILL to worker %d', worker.process.pid);
        process.kill(worker.process.pid, 'SIGKILL');
      } catch (e) {
        // this can happen.  don't crash!!
      }
    });
  }
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
793271
def stop(self):
        """"""

        msg = ''
        if self._process:
            _stop_process(self._process, 'Server process')
        else:
            msg += 'Server not started.\n'
        if msg:
            print(msg, end='')
1137165
def forkexec(argv, env=None):
    """"""
    child_pid = os.fork()
    if child_pid == 0:
        os.closerange(3, MAXFD)
        environ = os.environ.copy()
        if env is not None:
            environ.update(env)
        os.execve(argv[0], argv, environ)
    return child_pid
1207751
def _set_process_async(process):
    """"""
    for fd in [process.stderr.fileno(), process.stdout.fileno()]:
        fl = fcntl.fcntl(fd, fcntl.F_GETFL)
        fcntl.fcntl(fd, fcntl.F_SETFL, fl | os.O_NONBLOCK)
164450
def run_at_subprocess(self, use_subprocess, foo, *args, **kwrags):
        
        if use_subprocess is False:
            return foo(*args, **kwrags)

        child_pid = os.fork()
        if child_pid == 0:
            foo(*args, **kwrags)
            sys.exit(0)
        return os.waitpid(child_pid, 0)[1] == 0
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)
1331794
protected function handleWorkerExit()
    {
        $result = swoole_process::wait();

        if(!empty($this->_noRestartProcesses[$result['pid']])) {
            unset($this->_noRestartProcesses[$result['pid']]);
            return;
        }

        if($result['signal'] > 0) {
            if($this->restartPolicy & self::RESTART_ON_SIGNAL) {
                $this->forkOneWorker();
            }
        } else {
            if($result['code'] > 0) {
                $this->_errors[] = microtime(true);

                if($this->restartPolicy & self::RESTART_ON_ERROR && !$this->_disableRestartOnError) {
                    if($this->tooManyErrors()) {
                        //if exceed the maximum error frequency, stop forking new workers on error
                        $this->_disableRestartOnError = true;
                    } else {
                        $this->forkOneWorker();
                    }
                }
            } else {
                if($this->restartPolicy & self::RESTART_ON_EXIT) {
                    $this->forkOneWorker();
                }
            }
        }
    }