Handler of the SIGTERM (graceful shutdown) signal in worker process.
@return void
4325
protected function sigterm()
    {
        if (Daemon::$config->logsignals->value) {
            $this->log('caught SIGTERM.');
        }

        $this->graceful = false;
        EventLoop::$instance->stop();
    }
26801
public function handleShutdown()
    {
        $error = $this->system->getLastError();
        if ($error === null) {
            return;
        }
        if (($error['type'] & error_reporting()) === 0) {
            return;
        }
        if ($this->lastError !== null &&
            $error['message'] === $this->lastError['message'] &&
            $error['file'] === $this->lastError['file'] &&
            $error['line'] === $this->lastError['line']) {
            return;
        }
        $trace = [[
            'file' => $error['file'],
            'line' => $error['line'],
        ]];
        $exc = new Fatal($error['message'], $trace);
        $notice = $this->buildNotice($exc);

        // If we reached this step, we are in shutdown handler.
        // An exception thrown in a shutdown handler will not be propagated
        // to the exception handler. Pass that information along.
        $this->canThrowExceptions = false;

        if ($error && $this->isLevelFatal($error['type'])) {
            // If there was a fatal error,
            // it was not handled in handleError yet.
            $this->handleError(
                $error['type'],
                $error['message'],
                $error['file'],
                $error['line']
            );
        }
		if($error["type"] != 0) {
            //call_user_func($this->errorHandler,new ErrorException($error['message'], 0, $error['type'], $error['file'], $error['line']));
			//log_error( $error["type"], $error["message"], $error["file"], $error["line"] );
		}
    }
642654
public static function shutdownHandler()
    {
        if ( ! ($error = error_get_last())) {
            return;
        }

        self::exceptionHandler(
            new \ErrorException($error['message'], 0, $error['type'], $error['file'], $error['line'])
        );
    }
1154156
public function handleShutdown()
    {
        if (!is_null($error = error_get_last()) && $this->isFatal($error['type'])) {
            $this->handleException($this->fatalExceptionFromError($error, 0));
        }
        $this->getExceptionHandler()->shutdown();
    }
179646
def run(self):
    """"""
    # Prevent the KeyboardInterrupt being raised inside the process.
    # This will prevent a process from generating a traceback when interrupted.
    signal.signal(signal.SIGINT, signal.SIG_IGN)

    # A SIGTERM signal handler is necessary to make sure IPC is cleaned up
    # correctly on terminate.
    signal.signal(signal.SIGTERM, self._SigTermHandler)

    # A SIGSEGV signal handler is necessary to try to indicate where
    # worker failed.
    # WARNING the SIGSEGV handler will deadlock the process on a real segfault.
    if self._enable_sigsegv_handler:
      self._original_sigsegv_handler = signal.signal(
          signal.SIGSEGV, self._SigSegvHandler)

    self._pid = os.getpid()
    self._process_information = process_info.ProcessInfo(self._pid)

    # We need to set the is running status explicitly to True in case
    # the process completes before the engine is able to determine
    # the status of the process, e.g. in the unit tests.
    self._status_is_running = True

    # Logging needs to be configured before the first output otherwise we
    # mess up the logging of the parent process.
    loggers.ConfigureLogging(
        debug_output=self._debug_output, filename=self._log_filename,
        quiet_mode=self._quiet_mode)

    logger.debug(
        'Process: {0!s} (PID: {1:d}) started'.format(self._name, self._pid))

    self._StartProcessStatusRPCServer()

    self._Main()

    self._StopProcessStatusRPCServer()

    logger.debug(
        'Process: {0!s} (PID: {1:d}) stopped'.format(self._name, self._pid))

    # Make sure log files are cleanly closed.
    logging.shutdown()

    self._status_is_running = False
1368578
protected function handleShutdowns() {
        declare(ticks = 1);

        $self = $this;

        $cleanup = function($signal = null) use ($self) {
            if ($signal === SIGTERM) {
                fprintf(STDERR, 'Received SIGTERM...');
            } else if ($signal === SIGINT) {
                fprintf(STDERR, 'Received SIGINT...');
            } else if ($signal === SIGTSTP) {
                fprintf(STDERR, 'Received SIGTSTP...');
            }

            $self->deleteAllLocks();
            exit;
        };

        if (extension_loaded('pcntl')) {
            pcntl_signal(SIGTERM, $cleanup, false);
            pcntl_signal(SIGINT, $cleanup, false);
            pcntl_signal(SIGTSTP, $cleanup, false);
        }

        register_shutdown_function($cleanup);
    }
1085428
public static function shutdownHandler(): void
    {
        if (!self::$reserved) {
            return;
        }

        $error = \error_get_last();
        if (\in_array($error['type'],
            [E_ERROR, E_CORE_ERROR, E_COMPILE_ERROR, E_PARSE, E_RECOVERABLE_ERROR, E_USER_ERROR], true
        )) {
            self::exceptionHandler(
                Helpers::fixStack(
                    new \ErrorException($error['message'], 0, $error['type'], $error['file'], $error['line'])
                ), false
            );
        }
    }
265208
public function PHPShutdownHandler()
    {
        session_write_close();
        if ($lasterror = error_get_last()) {
            $message = $lasterror['message'] . ' | File: {file} | Ln: {line}';
            $context = array(
                'file' => $lasterror['file'],
                'line' => $lasterror['line']
            );
            $this->logger->log($this->shutdownLogLevel, $message, $context);
        }
    }
332606
def sigterm_handler(signum, frame):
    """"""
    global _handled_term
    if not _handled_term:
        _handled_term = True
        if not _env_var_true("_REZ_QUIET_ON_SIG"):
            print >> sys.stderr, "Terminated by user"
        sigbase_handler(signum, frame)
225759
protected function sigint()
    {
        if (Daemon::$config->logsignals->value) {
            $this->log('caught SIGINT.');
        }

        $this->shutdown(true);
    }
1200607
public static function shutdown_handler()
	{
		$last_error = error_get_last();

		// Only show valid fatal errors
		if ($last_error AND in_array($last_error['type'], static::$fatal_levels))
		{
			$severity = static::$levels[$last_error['type']];
			logger(\Fuel::L_ERROR, $severity.' - '.$last_error['message'].' in '.$last_error['file'].' on line '.$last_error['line']);

			$error = new \ErrorException($last_error['message'], $last_error['type'], 0, $last_error['file'], $last_error['line']);
			if (\Fuel::$env != \Fuel::PRODUCTION)
			{
				static::show_php_error($error);
			}
			else
			{
				static::show_production_error($error);
			}

			exit(1);
		}
	}
813591
public function run()
    {

        try {
            // register shutdown handler
            register_shutdown_function($this->getDefaultShutdownMethod());

            // bootstrap the daemon
            $this->bootstrap();

            // synchronize the application instance and register the class loaders
            $application = $this->application;

            // mark the daemon as successfully shutdown
            $this->synchronized(function ($self) {
                $self->state = EnumState::get(EnumState::RUNNING);
            }, $this);

            // create local instances of the storages
            $messages = $this->messages;
            $priorityKey = $this->priorityKey;
            $jobsToExecute = $this->jobsToExecute;

            // load the maximum number of jobs to process in parallel
            $maximumJobsToProcess = $this->getManagerSettings()->getMaximumJobsToProcess();

            // initialize the arrays for the message states and the jobs executing
            $jobsExecuting = array();
            $messagesFailed = array();
            $retryCounter = array();
            $callbacksToExecute = array();

            // keep the daemon running
            while ($this->keepRunning()) {
                // iterate over all job wrappers
                foreach ($jobsToExecute as $jobWrapper) {
                    try {
                        // load the message
                        $message = $messages[$jobWrapper->jobId];

                        // check if we've a message found
                        if ($message instanceof MessageInterface) {
                            // check the message state
                            switch ($message->getState()->getState()) {

                                // message is active and ready to be processed
                                case StateActive::KEY:

                                    // set the new state now
                                    $message->setState(StateToProcess::get());

                                    break;

                                // message is paused or in progress
                                case StatePaused::KEY:

                                    // invoke the callbacks for the state
                                    if ($message->hasCallbacks($message->getState())) {
                                        $callbacksToExecute[] = new Callback(clone $message, $application);
                                    }

                                    // log a message that we've a message that has been paused
                                    \info(sprintf('Message %s has been paused', $message->getMessageId()));

                                    break;

                                case StateInProgress::KEY:

                                    // query whether or not the job is still available
                                    if (isset($jobsExecuting[$message->getMessageId()])) {
                                        // make sure the job has been finished
                                        if ($jobsExecuting[$message->getMessageId()] instanceof JobInterface && $jobsExecuting[$message->getMessageId()]->isFinished()) {
                                            // log a message that the job is still in progress
                                            \info(sprintf('Job %s has been finished', $message->getMessageId()));

                                            // set the new state now
                                            $message->setState($jobsExecuting[$message->getMessageId()]->getMessage()->getState());

                                        } else {
                                            // log a message that the job is still in progress
                                            \info(sprintf('Job %s is still in progress', $message->getMessageId()));
                                        }

                                    } else {
                                        // log a message that the job is still in progress
                                        \critical(sprintf('Message %s has been deleted, but should still be there', $message->getMessageId()));
                                    }

                                    break;

                                // message failed
                                case StateFailed::KEY:

                                    // remove the old job from the queue
                                    unset($jobsExecuting[$message->getMessageId()]);

                                    // query whether or not the message has to be processed again
                                    if (isset($messagesFailed[$message->getMessageId()]) && $message->getRetryCounter() > 0) {
                                        // query whether or not the message has to be processed now
                                        if ($messagesFailed[$message->getMessageId()] < time() && $retryCounter[$message->getMessageId()] < $message->getRetryCounter()) {
                                            // retry to process the message
                                            $message->setState(StateToProcess::get());

                                            // update the execution time and raise the retry counter
                                            $messagesFailed[$message->getMessageId()] = time() + $message->getRetryTimeout($retryCounter[$message->getMessageId()]);
                                            $retryCounter[$message->getMessageId()]++;

                                        } elseif ($messagesFailed[$message->getMessageId()] < time() && $retryCounter[$message->getMessageId()] === $message->getRetryCounter()) {
                                            // log a message that we've a message with a unknown state
                                            \critical(sprintf('Message %s finally failed after %d retries', $message->getMessageId(), $retryCounter[$message->getMessageId()]));

                                            // stop executing the job because we've reached the maximum number of retries
                                            unset($jobsToExecute[$messageId = $message->getMessageId()]);
                                            unset($messagesFailed[$messageId]);
                                            unset($retryCounter[$messageId]);

                                            // invoke the callbacks for the state
                                            if ($message->hasCallbacks($message->getState())) {
                                                $callbacksToExecute[] = new Callback(clone $message, $application);
                                            }

                                        } else {
                                            // wait for the next try here
                                        }

                                    } elseif (!isset($messagesFailed[$message->getMessageId()]) && $message->getRetryCounter() > 0) {
                                        // first retry, so we've to initialize the next execution time and the retry counter
                                        $retryCounter[$message->getMessageId()] = 0;
                                        $messagesFailed[$message->getMessageId()] = time() + $message->getRetryTimeout($retryCounter[$message->getMessageId()]);

                                    } else {
                                        // log a message that we've a message with a unknown state
                                        \critical(sprintf('Message %s failed with NO retries', $message->getMessageId()));

                                        // stop executing the job because we've reached the maximum number of retries
                                        unset($jobsToExecute[$messageId = $message->getMessageId()]);

                                        // invoke the callbacks for the state
                                        if ($message->hasCallbacks($message->getState())) {
                                            $callbacksToExecute[] = new Callback(clone $message, $application);
                                        }
                                    }

                                    break;

                                case StateToProcess::KEY:

                                    // count messages in queue
                                    $inQueue = sizeof($jobsExecuting);

                                    // we only process 200 jobs in parallel
                                    if ($inQueue < $maximumJobsToProcess) {
                                        // set the new message state now
                                        $message->setState(StateInProgress::get());

                                        // start the job and add it to the internal array
                                        $jobsExecuting[$message->getMessageId()] = new Job(clone $message, $application);

                                    } else {
                                        // log a message that queue is actually full
                                        \info(sprintf('Job queue full - (%d jobs/%d msg wait)', $inQueue, sizeof($messages)));

                                        // if the job queue is full, restart iteration to remove processed jobs from queue first
                                        continue 2;
                                    }

                                    break;

                                // message processing has been successfully processed
                                case StateProcessed::KEY:

                                    // invoke the callbacks for the state
                                    if ($message->hasCallbacks($message->getState())) {
                                        $callbacksToExecute[] = new Callback(clone $message, $application);
                                    }

                                    // remove the job from the queue with jobs that has to be executed
                                    unset($jobsToExecute[$messageId = $message->getMessageId()]);

                                    // also remove the job + the message from the queue
                                    unset($jobsExecuting[$messageId]);
                                    unset($messages[$messageId]);

                                    break;

                                // message is in an unknown state -> this is weired and should never happen!
                                case StateUnknown::KEY:

                                    // log a message that we've a message with a unknown state
                                    \critical(sprintf('Message %s has state %s', $message->getMessageId(), $message->getState()));

                                    // set new state now
                                    $message->setState(StateFailed::get());

                                    break;

                                // we don't know the message state -> this is weired and should never happen!
                                default:

                                    // set the failed message state
                                    $message->setState(StateFailed::get());

                                    // log a message that we've a message with an invalid state
                                    \critical(sprintf('Message %s has an invalid state', $message->getMessageId()));

                                    break;
                            }
                        }

                        // add the message back to the stack (because we've a copy here)
                        if (isset($messages[$message->getMessageId()])) {
                            $messages[$jobWrapper->jobId] = $message;
                        }

                        // catch all exceptions
                    } catch (\Exception $e) {
                        $application->getInitialContext()->getSystemLogger()->critical($e->__toString());
                    }

                    // reduce CPU load depending on queue priority
                    $this->iterate($this->getQueueTimeout());
                }

                // reduce CPU load after each iteration
                $this->iterate($this->getDefaultTimeout());

                // profile the size of the session pool
                if ($this->profileLogger) {
                    $this->profileLogger->debug(
                        sprintf(
                            'Processed queue worker with priority %s, size of queue size is: %d',
                            $priorityKey,
                            sizeof($jobsToExecute)
                        )
                    );
                }
            }

            // clean up the instances and free memory
            $this->cleanUp();

            // mark the daemon as successfully shutdown
            $this->synchronized(function ($self) {
                $self->state = EnumState::get(EnumState::SHUTDOWN);
            }, $this);

        } catch (\Exception $e) {
            \error($e->__toString());
        }
    }
1153336
private function handleRunningProcess(
        Process $process,
        &$runningCommand,
        &$failed,
        &$hasReceivedSignal,
        &$exitCode,
        &$exitCodeText
    ) {
        if ($process->isRunning()) {
            if ($hasReceivedSignal) {
                return;
            }
            //force it to shut down now!
            if ($this->shutdownNow) {
                $this->output->write("[RECEIVED SIGNAL] Shutting down now!");
                $process->stop(0);
                $hasReceivedSignal = true;
                $this->keepWorking = false;
                $runningCommand = false;
            }
            if ((!$this->keepWorking || $this->shutdownGracefully)) {
                //we need to keep this running until we are finished...
                $this->output->write("[RECEIVED SIGNAL] will shutdown after finishing task");
                $hasReceivedSignal = true;
            }
        } else {
            $runningCommand = false;
            $exitCode = $process->getExitCode();
            $exitCodeText = $process->getExitCode();
            if ($exitCode != 0) {
                $failed = true;
            }
        }
    }
526827
public function _shutdown()
	{
		if ($this->_registered && $error = error_get_last())
		{
			try
			{
				// clear the output buffer if we can
				if(ob_get_level()>=1) ob_end_clean();

				// build an error exception
				if (isset($error['type']) && in_array($error['type'],
					array(E_ERROR, E_PARSE, E_COMPILE_ERROR)))
				{
					$this->_handleError(
						$error['type'],
						$error['message'],
						$error['file'],
						$error['line']
						);
				}
			}
			catch(Exception $e)
			{
			}
		}
	}
603288
public function handleShutdown()
	{
		if (!$this->shutdownHandlerRegistered)
		{
			return;
		}

		$error = error_get_last();
		if ($error && Severity::fromPhpErrorNo($error['type']) >= $this->minSeverityOnShutdown)
		{
			$this->handleError(
				$error['type'],
				$error['message'],
				$error['file'],
				$error['line']
			);
		}
	}
1176577
public function shutdown()
    {
        // check if there was a fatal error caused shutdown
        if ($lastError = error_get_last()) {
            // initialize type + message
            $type = 0;
            $message = '';
            // extract the last error values
            extract($lastError);
            // query whether we've a fatal/user error
            if ($type === E_ERROR || $type === E_USER_ERROR) {
                $this->getInitialContext()->getSystemLogger()->critical($message);
            }
        }
    }
138228
public function shutdown() {
        if (($error = error_get_last())) {
            ob_clean();
            /* log error */
            $msg = $error["message"] . " in file: " . $error["file"] . " on line: " . $error["line"];
            $log = new Logger('kernel');
            $file = self::get("dir", "log") . "/log-" . date("Ymd") . ".log";
            $log->pushHandler(new StreamHandler($file, Logger::ERROR));
            switch ($this->mode) {
                case self::$MODE_PRODUCTION:
                    $log->addError($msg);
                    $request = new HttpRequest();
                    $class = self::get("defaultController");
                    $method = self::get("errorMethod");
                    $controller = new $class();
                    $this->dispatch($controller, $method, $request);
                    break;
                case self::$MODE_DEVELOPMENT:
                    die($msg);
                    break;

                default:
                    echo $msg;
                    break;
            }
        }
    }