Handler for the SIGUSR2 (graceful restart all workers) signal in master process
@return void
544536
protected function sigusr2()
    {
        if (Daemon::$config->logsignals->value) {
            $this->log('Caught SIGUSR2 (graceful restart all workers).');
        }
        $this->signalToChildren(SIGUSR2);
    }
1038471
protected function listenForSignals()
    {
        pcntl_async_signals(true);

        pcntl_signal(SIGTERM, function () {
            $this->pendingSignals['terminate'] = 'terminate';
        });

        pcntl_signal(SIGUSR1, function () {
            $this->pendingSignals['restart'] = 'restart';
        });

        pcntl_signal(SIGUSR2, function () {
            $this->pendingSignals['pause'] = 'pause';
        });

        pcntl_signal(SIGCONT, function () {
            $this->pendingSignals['continue'] = 'continue';
        });
    }
68428
def install_signal_handlers(self):
        

        self.graceful_stop = False

        def request_shutdown_now():
            self.shutdown_now()

        def request_shutdown_graceful():

            # Second time CTRL-C, shutdown now
            if self.graceful_stop:
                self.shutdown_now()
            else:
                self.graceful_stop = True
                self.shutdown_graceful()

        # First time CTRL-C, try to shutdown gracefully
        gevent.signal(signal.SIGINT, request_shutdown_graceful)

        # User (or Heroku) requests a stop now, just mark tasks as interrupted.
        gevent.signal(signal.SIGTERM, request_shutdown_now)
571180
public function handleSignal($signal)
    {
        if (in_array($signal, $this->stopSignals)) {
            $this->logger->info(sprintf('Handle stop signal (%s)', $signal));
            $this->stop = true;
        } elseif (in_array($signal, $this->pauseSignals)) {
            $this->logger->info(sprintf('Handle pause signal (%s)', $signal));
            $this->pause = true;
        } elseif (in_array($signal, $this->resumeSignals)) {
            $this->logger->info(sprintf('Handle resume signal (%s)', $signal));
            $this->pause = false;
        }
    }
1159395
public static function stopAll()
    {
        self::$_status = self::STATUS_SHUTDOWN;
        // For master process.
        if (self::$_masterPid === getmypid()) {
            self::log("Workerman[" . basename(self::$_startFile) . "] Stopping ...");
            $worker_pid_array = self::getAllWorkerPids();
            // Send stop signal to all child processes.
            foreach ($worker_pid_array as $worker_pid) {
                swoole_process::kill($worker_pid, SIGINT);
                Timer::add(self::KILL_WORKER_TIMER_TIME, array('\swoole_process','kill'), array($worker_pid, SIGKILL), false);
            }
            // Remove statistics file.
            if (is_file(self::$_statisticsFile)) {
                @unlink(self::$_statisticsFile);
            }
        } // For child processes.
        else {
            // Execute exit.
            foreach (self::$_workers as $worker) {
                $worker->stop();
            }
            self::$globalEvent->destroy();
            exit(0);
        }
    }
820081
protected static function reload()
    {
        // For master process.
        if (self::$_masterPid === posix_getpid()) {
            // Set reloading state.
            if (self::$_status !== self::STATUS_RELOADING && self::$_status !== self::STATUS_SHUTDOWN) {
                self::log("Workerman[" . basename(self::$_startFile) . "] reloading");
                self::$_status = self::STATUS_RELOADING;
                // Try to emit onMasterReload callback.
                if (self::$onMasterReload) {
                    try {
                        call_user_func(self::$onMasterReload);
                    } catch (\Exception $e) {
                        self::log($e);
                        exit(250);
                    } catch (\Error $e) {
                        self::log($e);
                        exit(250);
                    }
                    self::initId();
                }
            }

            // Send reload signal to all child processes.
            $reloadable_pid_array = array();
            foreach (self::$_pidMap as $worker_id => $worker_pid_array) {
                $worker = self::$_workers[$worker_id];
                if ($worker->reloadable) {
                    foreach ($worker_pid_array as $pid) {
                        $reloadable_pid_array[$pid] = $pid;
                    }
                } else {
                    foreach ($worker_pid_array as $pid) {
                        // Send reload signal to a worker process which reloadable is false.
                        swoole_process::kill($pid, SIGUSR1);
                    }
                }
            }

            // Get all pids that are waiting reload.
            self::$_pidsToRestart = array_intersect(self::$_pidsToRestart, $reloadable_pid_array);

            // Reload complete.
            if (empty(self::$_pidsToRestart)) {
                if (self::$_status !== self::STATUS_SHUTDOWN) {
                    self::$_status = self::STATUS_RUNNING;
                }
                return;
            }
            // Continue reload.
            $one_worker_pid = current(self::$_pidsToRestart);
            // Send reload signal to a worker process.
            swoole_process::kill($one_worker_pid, SIGUSR1);
            // If the process does not exit after self::KILL_WORKER_TIMER_TIME seconds try to kill it.
            Timer::add(self::KILL_WORKER_TIMER_TIME, array('\swoole_process','kill'), array($one_worker_pid, SIGKILL), false);
        } // For child processes.
        else {
            $worker = current(self::$_workers);
            // Try to emit onWorkerReload callback.
            if ($worker->onWorkerReload) {
                try {
                    call_user_func($worker->onWorkerReload, $worker);
                } catch (\Exception $e) {
                    self::log($e);
                    exit(250);
                } catch (\Error $e) {
                    self::log($e);
                    exit(250);
                }
            }

            if ($worker->reloadable) {
                self::stopAll();
            }
        }
    }
721712
public function run()
    {
        //Update process state.
        static::$_status = static::STATUS_RUNNING;

        // Register shutdown function for checking errors.
        register_shutdown_function(array("\\Workerman\\Worker", 'checkErrors'));

        // Set autoload root path.
        Autoloader::setRootPath($this->_autoloadRootPath);

        // Create a global event loop.
        if (!static::$globalEvent) {
            $event_loop_class = static::getEventLoopName();
            static::$globalEvent = new $event_loop_class;
            $this->resumeAccept();
        }

        // Reinstall signal.
        static::reinstallSignal();

        // Init Timer.
        Timer::init(static::$globalEvent);

        // Set an empty onMessage callback.
        if (empty($this->onMessage)) {
            $this->onMessage = function () {};
        }

        restore_error_handler();
        
        // Try to emit onWorkerStart callback.
        if ($this->onWorkerStart) {
            try {
                call_user_func($this->onWorkerStart, $this);
            } catch (\Exception $e) {
                static::log($e);
                // Avoid rapid infinite loop exit.
                sleep(1);
                exit(250);
            } catch (\Error $e) {
                static::log($e);
                // Avoid rapid infinite loop exit.
                sleep(1);
                exit(250);
            }
        }

        // Main loop.
        static::$globalEvent->loop();
    }
187866
def sigusr1_handler(self, unused_signum, unused_frame):
        
        for process in self.processes:
            if process.pid and os.getpid() == self.main_pid:
                try:
                    os.kill(process.pid, signal.SIGUSR1)
                except ProcessLookupError:
                    pass
        if self._sigusr1_handler_func is not None:
            self._sigusr1_handler_func(self.context)
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']);
        }
    }
1067417
public function run()
    {
        if (empty($this->queues)) {
            die('Set queues var containing the list of queues to work.' . PHP_EOL);
        }

        Resque::setBackend($this->redisBackend, $this->database, $this->password);

        if ($this->count > 1) {
            for ($i = 0; $i < $this->count; ++$i) {
                $pid = pcntl_fork();
                if ($pid == -1) {
                    die('Could not fork worker ' . $i . PHP_EOL);
                } elseif (!$pid) {
                    // Child, start the worker
                    $this->_startWorker();
                    break;
                }
            }
        } else {
            if (!empty($this->pidFile)) {
                file_put_contents($this->pidFile, getmypid()) or
                    die('Could not write PID information to ' . $PIDFILE . PHP_EOL);
            }
            // Start a single worker
            $this->_startWorker();
        }
    }
25305
public function resume()
    {
        $this->paused = false;

        if($this->getProcess()->getPid() == getmypid()) {
            $this->getLogger()->notice('SIGCONT received; resuming job processing');
        }else{
            $this->getProcess()->kill(SIGCONT);
        }
    }
1375033
public function complete()
    {
        $this->stopped();

        $this->setStatus(Job::STATUS_COMPLETE);

        $this->redis->zadd(Queue::redisKey($this->queue, 'processed'), time(), $this->payload);
        Stats::incr('processed', 1);
        Stats::incr('processed', 1, Queue::redisKey($this->queue, 'stats'));

        Event::fire(Event::JOB_COMPLETE, $this);
    }
1026535
public function signal_handler_sigint($signal_number)
	{
		// log that we received an exit request
		$this->received_exit_request(true);

		// kill child processes
		if (self::$parent_pid == getmypid())
		{
			foreach ($this->forked_children as $pid => &$pid_info)
			{
				if ($pid_info['status'] == self::STOPPED)
				{
					continue;
				}

				// tell helpers not to respawn
				if ($pid_info['status'] == self::HELPER)
				{
					$pid_info['respawn'] = false;
				}

				$this->safe_kill($pid, SIGINT, 'requesting child exit for pid: ' . $pid, self::LOG_LEVEL_INFO);
			}

			sleep(1);

			// checking for missed sigchild
			$this->signal_handler_sigchild(SIGCHLD);

			$start_time = time();

			// wait for child processes to go away
			while ($this->forked_children_count > 0)
			{
				if (time() > ($start_time + $this->children_max_timeout))
				{
					foreach ($this->forked_children as $pid => $child)
					{
						if ($child['status'] == self::STOPPED)
						{
							continue;
						}

						$this->safe_kill($pid, SIGKILL, 'force killing child pid: ' . $pid, self::LOG_LEVEL_INFO);

						// stop the child
						$this->forked_children[$pid]['status'] = self::STOPPED;
						$this->forked_children_count--;
					}
				}
				else
				{
					$this->log('waiting ' . ($start_time + $this->children_max_timeout - time()) . ' seconds for ' . $this->forked_children_count . ' children to clean up', self::LOG_LEVEL_INFO);
					sleep(1);
					$this->housekeeping_check();
				}
			}

			// make call back to parent exit function if it exists
			$this->invoke_callback($this->parent_function_exit, $parameters = array(self::$parent_pid, $signal_number), true);
		}
		else
		{
			// invoke child cleanup callback
			if (isset($this->child_bucket))
			{
				$this->invoke_callback($this->child_function_exit[$this->child_bucket], $parameters = array($this->child_bucket), true);
			}
		}

		exit(-1);
	}
361172
def handle_signal(self, sig, frame):
        """"""
        if sig in [signal.SIGINT]:
            log.warning("Ctrl-C pressed, shutting down...")
        if sig in [signal.SIGTERM]:
            log.warning("SIGTERM received, shutting down...")
        self.cleanup()
        sys.exit(-sig)
579137
public static function stopAll()
    {
        static::$_status = static::STATUS_SHUTDOWN;
        // For master process.
        if (static::$_masterPid === posix_getpid()) {
            static::log("Workerman[" . basename(static::$_startFile) . "] stopping ...");
            $worker_pid_array = static::getAllWorkerPids();
            // Send stop signal to all child processes.
            if (static::$_gracefulStop) {
                $sig = SIGTERM;
            } else {
                $sig = SIGINT;
            }
            foreach ($worker_pid_array as $worker_pid) {
                posix_kill($worker_pid, $sig);
                if(!static::$_gracefulStop){
                    Timer::add(static::KILL_WORKER_TIMER_TIME, 'posix_kill', array($worker_pid, SIGKILL), false);
                }
            }
            Timer::add(1, "\\Workerman\\Worker::checkIfChildRunning");
            // Remove statistics file.
            if (is_file(static::$_statisticsFile)) {
                @unlink(static::$_statisticsFile);
            }
        } // For child processes.
        else {
            // Execute exit.
            foreach (static::$_workers as $worker) {
                if(!$worker->stopping){
                    $worker->stop();
                    $worker->stopping = true;
                }
            }
            if (!static::$_gracefulStop || ConnectionInterface::$statistics['connection_count'] <= 0) {
                static::$_workers = array();
                if (static::$globalEvent) {
                    static::$globalEvent->destroy();
                }
                exit(0);
            }
        }
    }
435168
public function stop()
    {
        $this->shutdown = true;
        if($this->getProcess()->getPid() == getmypid()) {
            $this->getLogger()->notice('Worker {worker} shutting down', array('worker' => $this));
        }else{
            $this->getProcess()->kill(SIGQUIT);
        }
    }
4325
protected function sigterm()
    {
        if (Daemon::$config->logsignals->value) {
            $this->log('caught SIGTERM.');
        }

        $this->graceful = false;
        EventLoop::$instance->stop();
    }