Checks the current PHP process against the limits specified in a daemon
options object. This function will also throw an exception if the daemon
has been flagged for shutdown.

@throws ShutdownException When limits in the daemon options are exceeded
438937
private function checkDaemonLimits(): void
    {
        if ($this->isShutdown) {
            throw new ShutdownException($this->shutdownMessage);
        }

        pcntl_signal_dispatch();

        if (DaemonOptions::NO_LIMIT !== $this->requestLimit) {
            if ($this->requestLimit <= $this->requestCount) {
                throw new ShutdownException('Daemon request limit reached ('.$this->requestCount.' of '.$this->requestLimit.')');
            }
        }

        if (DaemonOptions::NO_LIMIT !== $this->memoryLimit) {
            $memoryUsage = memory_get_usage(true);

            if ($this->memoryLimit <= $memoryUsage) {
                throw new ShutdownException('Daemon memory limit reached ('.$memoryUsage.' of '.$this->memoryLimit.' bytes)');
            }
        }
    }
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)
			{
			}
		}
	}
1335699
public function checkRequestLimit()
  {
    $isLimitReached = false;
    $client     = $this->getClient();
    
    if ( ! is_null($client)) {
      $currentTotalRequest = 1;
      $currentTime     = time();
      $requestLimitUntil   = $currentTime;
      
      $requestLimitUntil = strtotime($client->request_limit_until);
      if ($requestLimitUntil < 0) {
        $requestLimitUntil = $currentTime;
      }

      if ($currentTime <= $requestLimitUntil) {
        $currentTotalRequest = $client->current_total_request + 1;

        if ($currentTotalRequest > $client->request_limit) {
          $isLimitReached = true;
        }
      }

      if ($currentTime > $requestLimitUntil) {
        $dateTime = new DateTime('+1 hour');

        $requestLimitUntil = $dateTime->getTimestamp();

        unset($dateTime);
      }

      if ( ! $isLimitReached) {
        $dateTime = new DateTime();

        $client->current_total_request = $currentTotalRequest;
        $client->request_limit_until   = $dateTime->setTimestamp($requestLimitUntil)->format('Y-m-d H:i:s');
        $client->last_request_at     = $dateTime->setTimestamp($currentTime)->format('Y-m-d H:i:s');

        $client->save();

        unset($dateTime);
      }
    }

    unset($client);

    return $isLimitReached;
  }
1165786
public static function shutdown()
    {
        $last_error = error_get_last();

        if (!is_null($last_error) && $last_error['type'] === E_ERROR) {
            $code = $last_error['type'];
            $message = $last_error['message'];
            $file = $last_error['file'];
            $line = $last_error['line'];

            try {
                // Log the error message
                if (self::$_Log instanceof Log) {
                    self::$_Log->pushToLog(sprintf(
                        '%s %s: %s%s%s',
                        __CLASS__,
                        $code,
                        $message,
                        ($line ? " on line $line" : null),
                        ($file ? " of file $file" : null)
                    ), $code, true);
                }

                ob_clean();

                // Display the error message
                echo self::renderHtml(
                    'fatalerror.fatal',
                    'Fatal Error',
                    $message,
                    $file,
                    $line
                );
            } catch (Exception $e) {
                echo "<pre>";
                echo 'A severe error occurred whilst trying to handle an exception, check the Symphony log for more details' . PHP_EOL;
                echo $e->getMessage() . ' on ' . $e->getLine() . ' of file ' . $e->getFile() . PHP_EOL;
            }
        }
    }
699541
public function shutdown()
    {
        // dispatch shutdown event
        $applicationEvent = $this->getApplicationEvent();
        $applicationEvent->setName(self::EVENT_SYSTEM_SHUTDOWN);
        $this->emit($applicationEvent);

        exit((int)$this->isError());
    }
582867
static public function _registered_shutdown()
	{
		if( self::$_byPassCallBacks )
		{
			return;
		}
		#- first sort the stack
		uasort( self::$_registeredCallbacks, array( __class__, '_compare' ) );
		foreach( self::$_registeredCallbacks as $cb )
		{
			call_user_func_array( $cb[ 0 ], $cb[ 3 ] );
		}
	}
512436
@Override
    public void registerLimit(final long limit) {

        if (queues.size() > 0) {
            if (unlimited.get(currentQueue())
                         .get())
                limits.get(currentQueue())
                      .set(0);

            limits.get(currentQueue())
                  .addAndGet(limit);
            unlimited.get(currentQueue())
                     .set(false);

            queues.stream()
                  .forEach(this::closeQueueIfFinishedStateless);

        }
    }
368809
function shutdown()
    {
        if ($this->exception_handler_called) {
            return;
        }

        if (ob_get_level() > 0)
            ob_get_flush();

        if ($this->level) {
            echo ($this->terminal ? PHP_EOL : '<br>');
            $t  = microtime(true) - $_SERVER['REQUEST_TIME_FLOAT'];
            $te = sprintf(' %.2f mili sec.', $t * 1000);
            self::dump('Elapsed time: ' . $te, 0);
        }

        if ($this->level > 1) {
            $files = get_included_files();
            self::dump($files, 0);
        }
    }
270897
public function stop()
    {

        // log a message that we're waiting for shutdown
        $this->log(LogLevel::INFO, sprintf('Now start to shutdown daemon %s', get_class($this)));

        // load the default timeout to wait for daemon shutdown
        $shutdownTimeout = $this->getDefaultShutdownTimeout();

        // start shutdown process
        $this->synchronized(function ($self) {
            $self->state = EnumState::get(EnumState::HALT);
        }, $this);

        do {
            // log a message that we're waiting for shutdown
            $this->log(LogLevel::INFO, sprintf('Wait for shutdown daemon %s', get_class($this)));

            // query whether state key is SHUTDOWN or not
            $waitForShutdown = $this->state->notEquals(EnumState::get(EnumState::SHUTDOWN));

            // sleep and wait for successfull daemon shutdown
            $this->sleep($shutdownTimeout);

        } while ($waitForShutdown);

        // log a message that we're waiting for shutdown
        $this->log(LogLevel::INFO, sprintf('Successfully shutdown daemon %s', get_class($this)));
    }
1278947
public void shutdownNow() {
      log.tracef("Stopping limited executor %s", name);
      running = false;
      lock.lock();
      try {
         queue.clear();

         for (Thread t : threads.keySet()) {
            t.interrupt();
         }
      } finally {
         lock.unlock();
      }
   }
359822
protected function shutdown($restart = false)
    {
        // If we are already exiting, chill.
        if ($this->exiting) {
            return;
        } else // If not, now we are.
        {
            $this->exiting = true;
        }

        // If we aren't already daemonized then just kill the application.
        if (!$this->running && !$this->isActive()) {
            $this->getLogger()->info('Process was not daemonized yet, just halting current process');

            $this->close();
        }

        // Only read the pid for the parent file.
        if ($this->parentId == $this->processId) {
            // Read the contents of the process id file as an integer.
            $fp = fopen($this->config->get('application_pid_file'), 'r');
            $pid = fread($fp, filesize($this->config->get('application_pid_file')));
            $pid = (int) $pid;
            fclose($fp);

            // Remove the process id file.
            @ unlink($this->config->get('application_pid_file'));

            // If we are supposed to restart the daemon we need to execute the same command.
            if ($restart) {
                $this->close(exec(implode(' ', $GLOBALS['argv']) . ' > /dev/null &'));
            } else // If we are not supposed to restart the daemon let's just kill -9.
            {
                passthru('kill -9 ' . $pid);
                $this->close();
            }
        }
    }
685125
public function stop() : bool
    {
        $serverPid = $this->getServerPid();
        if ($serverPid === 0) {
            return true;
        }
        $response = $this->sendCommand('stop');
        if ($response !== 'ok') {
            throw new ControlException('Shutdown failed.');
        }
        return true;
    }
47610
public function endProcess()
    {
        if (isset($this->_process)) {
            $error = $this->getError();
            foreach (array_keys($this->_pipes) as $descriptor) {
                $this->closeResource($descriptor);
            }
            $return = proc_close($this->_process);
            if ($return !== 0) {
                throw new CException(sprintf('Process failed with error "%s"', $error), $return);
            }
            $this->_process = null;
            echo "done\n";
            return $return;
        }
        return 0;
    }
102992
public static function handlerShutdown()
    {
        $error = error_get_last();
        if($error !== NULL) {
            self::handlerError($error['type'], '[SHUTDOWN] ' . $error['message'], $error['file'], $error['line']);
        }
    }
90927
public function stop()
    {
        if ($this->pid) {
            exec('kill ' . $this->pid, $output, $ret);
            if ($ret !== 0) {
                throw new Exception('Error stopping build-in server.');
            }
            $this->pid = null;
        }
    }
691815
public static function ShutdownHandler () {
		$error = error_get_last();
		if (isset($error['type'])) static::Exception($error);
		if (!self::isHtmlResponse() || count(self::$dumps) === 0) return;
		list($dumps, $lastDump) = self::formatDebugDumps();
		echo str_replace(
			['%mvccoreDumps%', '"%mvccoreInitArgs%"'],
			[$dumps, ($lastDump ? '!0' : '!1') . ',' . count(self::$dumps)],
			file_get_contents(__DIR__.'/debug.html')
		);
	}
290586
public function stop(): bool
    {
        $this->process->getPid()->onResolve(function ($error, $pid) {
            if ($error) {
                throw new ProcessException($error);
            }

            print "\nStopping Process Id: {$pid}\n";

            if ('\\' === \DIRECTORY_SEPARATOR) {
                \exec(\sprintf('taskkill /F /T /PID %d 2>&1', $pid), $output, $exitCode);
                if ($exitCode) {
                    throw new ProcessException(\sprintf('Unable to kill the process (%s).', \implode(' ', $output)));
                }
            } else {
                $this->process->signal(15);

                if ($ok = \proc_open("kill $pid", [2 => ['pipe', 'w']], $pipes)) {
                    $ok = false === \fgets($pipes[2]);
                }

                if (!$ok) {
                    throw new ProcessException(\sprintf('Error while killing process "%s".', $pid));
                }
            }

            $this->process->kill();
        });

        return true;
    }