Register signal handlers that a worker should respond to.

TERM/INT/QUIT: Shutdown after the current job is finished then exit.
USR2: Pause worker, no new jobs will be processed but the current one will be finished.
CONT: Resume worker.
359724
private function registerSigHandlers()
    {
        if (!function_exists('pcntl_signal')) {
            $this->logError('Please make sure that "pcntl" is enabled.', $this->getLogContext());
            throw new \RuntimeException('Please make sure that "pcntl" is enabled.');
        }

        declare(ticks = 1);

        pcntl_signal(SIGTERM, array($this, 'shutdown'));
        pcntl_signal(SIGINT, array($this, 'shutdown'));
        pcntl_signal(SIGQUIT, array($this, 'shutdown'));
        pcntl_signal(SIGUSR2, array($this, 'pauseProcessing'));
        pcntl_signal(SIGCONT, array($this, 'unPauseProcessing'));

        $this->logDebug('Finished setting up signal handlers', $this->getLogContext());
    }
842255
function signals() {

  /**
   *  Signal handler.
   */
  function interrupt(signal) {
    this.log.notice('received %s, scheduling shutdown', signal);
    this.shutdown(0, process.exit);
  }

  interrupt = interrupt.bind(this);

  function iterate(signal) {

    /* test environment listener leak */
    if(process.listeners(signal).length) return;

    process.once(signal, function() {
      interrupt(signal);
    })
  }

  ['SIGINT', 'SIGTERM'].forEach(iterate.bind(this));
}
58418
def handle_signal(signal)
      info "Got signal #{signal}"
      case signal
      when 'TERM', 'INT', 'SHUTDOWN' # shutdown is an internal command
        info 'Shutting down...'
        # EM.stop if EventMachine.reactor_running?
        @plugins.stop
        @supervisor.shutdown
        true
      when 'TTIN'
        Thread.list.each do |thread|
          warn "Thread #{thread.object_id.to_s(36)} #{thread['label']}"
          if thread.backtrace
            warn thread.backtrace.join("\n")
          else
            warn 'no backtrace available'
          end
        end
        false
      end
    end
967896
def setup_signal_handlers(self):
        ''''''
        if platform.system() == 'Windows':
            _logger.warning(_(
                'Graceful stopping with Unix signals is not supported '
                'on this OS.'
            ))
            return

        event_loop = asyncio.get_event_loop()
        graceful_called = False

        def graceful_stop_callback():
            nonlocal graceful_called

            if graceful_called:
                forceful_stop_callback()
                return

            graceful_called = True

            _logger.info(_('Stopping once all requests complete...'))
            _logger.info(_('Interrupt again to force stopping immediately.'))
            self.stop()

        def forceful_stop_callback():
            _logger.info(_('Forcing immediate stop...'))
            logging.raiseExceptions = False
            event_loop.stop()

        event_loop.add_signal_handler(signal.SIGINT, graceful_stop_callback)
        event_loop.add_signal_handler(signal.SIGTERM, forceful_stop_callback)
744340
def handle_control_command(command)
      exit_reason = nil
      if command.cancel_signal?
        UI.verbose("received cancel signal shutting down, reason: #{command.reason}")

        # send an ack to the client to let it know we're shutting down
        cancel_response = '{"payload":{"status":"cancelled"}}'
        send_response(cancel_response)

        exit_reason = :cancelled
      elsif command.done_signal?
        UI.verbose("received done signal shutting down")

        # client is already in the process of shutting down, no need to ack
        exit_reason = :done
      end

      # if the command came in with a user-facing message, display it
      if command.user_message
        UI.important(command.user_message)
      end

      # currently all control commands should trigger a disconnect and shutdown
      handle_disconnect(error: false, exit_reason: exit_reason)
      return COMMAND_EXECUTION_STATE[:already_shutdown]
    end
649774
def _signal_handler(self, *_) -> None:
        
        if self._num_signals == 0:
            logging.warning('Interrupt signal caught - training will be terminated')
            logging.warning('Another interrupt signal will terminate the program immediately')
            self._num_signals += 1
        else:
            logging.error('Another interrupt signal caught - terminating program immediately')
            sys.exit(2)
762846
def go_ham
      loop do
        read_listeners
        reap_all_listeners(Process::WNOHANG)
        start_listener unless @paused
        case signal = SIGNAL_QUEUE.shift
        when nil
          yawn(@listener_backoff.how_long? || 30.0)
        when :INFO
          dump_object_counts
        when :HUP
          reopen_logs
          log "Restarting listener with new configuration and application."
          prepare_new_listener
        when :USR2
          log "Pause job processing"
          @paused = true
          kill_listener(:QUIT, @current_listener)
          @current_listener = nil
        when :CONT
          log "Resume job processing"
          @paused = false
          kill_all_listeners(:CONT)
        when :INT, :TERM, :QUIT
          log "Shutting down..."
          kill_all_listeners(signal)
          wait_for_workers unless @fast_exit
          break
        end
      end
    end
834804
def interrupt(self):
        
        ident = self.ident()
        print('{} for "{}" saw interrupt. Finishing in-progress task.'.format(
            ident,
            self.to_consume
        ))
671578
function checkRestartQueue() {
            // Kill one worker only if maximum count are working.
            if (restartQueue.length > 0 && listeningWorkersCount === workersCount && !currentRestartingPid) {
                var pid = restartQueue.shift();
                try {
                    // Store process id to wait for its finish.
                    currentRestartingPid = pid;
                    // Send SIGTERM signal to worker. SIGTERM starts graceful shutdown of worker inside it.
                    process.kill(pid);

                } catch(ex) {

                    // Reset current pid.
                    currentRestartingPid = null;

                    // If no process killed, try next in queue.
                    process.nextTick(checkRestartQueue);

                    // Fail silent on 'No such process'. May occur when kill message received after kill initiated but not finished.
                    if (ex.code !== 'ESRCH') {
                        throw ex;
                    }
                }
            }
        }
442052
public function start()
    {
        declare (ticks = 1);
        register_shutdown_function(array($this, "shutdown"));
        pcntl_signal(SIGTERM, array($this, "signalHandler"));
        pcntl_signal(SIGINT, array($this, "signalHandler"));

        $this->output->writeln("<info>Starting <comment>".$this->config->getName()."</comment>.</info>");

        $this->dispatcher->dispatch(WorkerEvents::STARTED, new WorkerStartedEvent($this));

        // A dummy timer to keep a process on a system.
        $this->eventLoop->addPeriodicTimer(10, function () {});

        $this->output->writeln('<info>Successfully booted. Quit working with CONTROL-C.</info>');

        // Start event loop.
        $this->eventLoop->run();
    }
960919
def graceful_stop(self, signal_number=None, stack_frame=None):
        
        stop_msg = "Hard" if self.shutdown else "Graceful"
        if signal_number is None:
            self.log.info("%s stop called manually. "
                          "Shutting down.", stop_msg)
        else:
            self.log.info("%s stop called by signal #%s. Shutting down."
                          "Stack Frame: %s",
                          stop_msg, signal_number, stack_frame)
        self.shutdown = True
        self.crawler_list.stop()
        self.daemon_list.stop()
        self.thread_event.set()
        return True
570237
def worker_finished(pid)
      worker_status(pid, 'stop')
      all_listeners.each do |other|
        other.worker_finished(pid)
      end
    end
1142988
def shutdown(self, wait=True):
        
        self.scheduler_thread.stop()
        self.worker_message_handler_thread.stop()

        if wait:
            self.scheduler_thread.join()
            self.worker_message_handler_thread.join()
269773
public synchronized void stop(boolean interruptHandlers) {
    LOG.info("Stopping server on " + port);
    
    if (!interruptHandlers) {
      // keep responder working
      responder.responderExtension = true;
      // do not purge connections in listener
      listener.cleanConnectionsAfterShutdown = false;
    } else {
      responder.interrupt();
    }
    
    running = false;
    if (interruptHandlers && handlers != null) {
      for (int i = 0; i < handlerCount; i++) {
        if (handlers[i] != null) {
          handlers[i].interrupt();
        }
      }
    }

    listener.interrupt();
    listener.doStop();
    notifyAll();
    if (this.rpcMetrics != null) {
      this.rpcMetrics.shutdown();
    }
  }
815312
protected function sigtstp()
    {
        if (Daemon::$config->logsignals->value) {
            $this->log('Caught SIGTSTP (graceful stop all workers).');
        }

        $this->signalToChildren(SIGTSTP);
        $this->shutdown(SIGTSTP);
    }
594225
public static function initialize() {
        if (self::$registered) {
            debugging('Shutdown manager is already initialised!');
        }
        self::$registered = true;
        register_shutdown_function(array('core_shutdown_manager', 'shutdown_handler'));

        // Signal handlers should only be used when dealing with a CLI script.
        // In the case of PHP called in a web server the server is the owning process and should handle the signal chain
        // properly itself.
        // The 'pcntl' extension is optional and not available on Windows.
        if (CLI_SCRIPT && extension_loaded('pcntl') && function_exists('pcntl_async_signals')) {
            // We capture and handle SIGINT (Ctrl+C) and SIGTERM (termination requested).
            pcntl_async_signals(true);
            pcntl_signal(SIGINT, ['core_shutdown_manager', 'signal_handler']);
            pcntl_signal(SIGTERM, ['core_shutdown_manager', 'signal_handler']);
        }
    }
538701
public synchronized void shutDown() {

        int count = 0;
        // if the handler is still running, we must wait up to 30 seconds until it is finished
        while ((count < HANDLER_FINISH_TIME) && m_handler.isBusy()) {
            count++;
            try {
                if (CmsLog.INIT.isInfoEnabled()) {
                    CmsLog.INIT.info(
                        Messages.get().getBundle().key(
                            Messages.INIT_STATIC_EXPORT_SHUTDOWN_3,
                            m_handler.getClass().getName(),
                            String.valueOf(count),
                            String.valueOf(HANDLER_FINISH_TIME)));
                }
                wait(1000);
            } catch (InterruptedException e) {
                // if interrupted we ignore the handler, this will produce some log messages but should be ok
                count = HANDLER_FINISH_TIME;
            }
        }

        if (CmsLog.INIT.isInfoEnabled()) {
            CmsLog.INIT.info(Messages.get().getBundle().key(Messages.INIT_SHUTDOWN_1, this.getClass().getName()));
        }

    }