/** * Executes the current command. * * @param InputInterface $input An InputInterface instance * @param OutputInterface $output An OutputInterface instance * * @return integer 0 if everything went fine, or an error code * * @throws \InvalidArgumentException When the number of messages to consume is less than 0 * @throws \InvalidArgumentException When the pcntl is not installed and option -s is true */ protected function execute(InputInterface $input, OutputInterface $output) { if (defined('AMQP_WITHOUT_SIGNALS') === false) { define('AMQP_WITHOUT_SIGNALS', $input->getOption('without-signals')); } if (!AMQP_WITHOUT_SIGNALS && extension_loaded('pcntl')) { if (!function_exists('pcntl_signal')) { throw new \BadFunctionCallException("This function is referenced in the php.ini 'disable_functions' and can't be called."); } pcntl_signal(SIGTERM, array(&$this, 'stopConsumer')); pcntl_signal(SIGINT, array(&$this, 'stopConsumer')); pcntl_signal(SIGHUP, array(&$this, 'restartConsumer')); } if (defined('AMQP_DEBUG') === false) { define('AMQP_DEBUG', (bool) $input->getOption('debug')); } $this->amount = $input->getOption('messages'); if (0 > $this->amount) { throw new \InvalidArgumentException("The -m option should be null or greater than 0"); } $this->consumer = $this->getContainer()->get(sprintf($this->getConsumerService(), $input->getArgument('name'))); if (!is_null($input->getOption('memory-limit')) && ctype_digit((string) $input->getOption('memory-limit')) && $input->getOption('memory-limit') > 0) { $this->consumer->setMemoryLimit($input->getOption('memory-limit')); } $this->consumer->setRoutingKey($input->getOption('route')); $this->consumer->consume($this->amount); }
/** * Execute command * * @param InputInterface $input Input * @param OutputInterface $output Output * * @return null|integer null or 0 if everything went fine, or an error code */ protected function execute(InputInterface $input, OutputInterface $output) { $logger = $this->getLogger(); // Check if another queue-runner is already running. if (false !== ($pid = $this->isRunning())) { $logger->debug(sprintf('Queue Runner still running (PID %d)', $pid)); return 0; } $logger->notice(sprintf('Queue Runner started (PID %d)', getmypid())); // Get concurrency $this->concurrency = $this->getContainer()->getParameter('kuborgh_queue.concurrency'); // Initial cleanup of stalled jobs $this->cleanStalledJobs(); // Initial cleanup of jobs stalled at starting $this->cleanStalledStartingJobs(); // Catch Kill signals declare (ticks=100); pcntl_signal(SIGINT, array($this, 'sigHandler')); pcntl_signal(SIGTERM, array($this, 'sigHandler')); do { // Check queue $abort = $this->checkQueue(); } while ($this->running && !$abort); $logger->notice(sprintf('Queue Runner terminated (PID %d)', getmypid())); return 0; }
private function bindSignals() { pcntl_signal(SIGTERM, [$this, "sigHandler"]); pcntl_signal(SIGINT, [$this, "sigHandler"]); //zombie-process solution pcntl_signal(SIGCHLD, [$this, 'childSignalHandler']); }
/** * * @param InputInterface $input * @param OutputInterface $output * * @return void */ protected function initialize(InputInterface $input, OutputInterface $output) { parent::initialize($input, $output); declare (ticks=1); pcntl_signal(SIGTERM, [$this, 'stopCommand']); pcntl_signal(SIGINT, [$this, 'stopCommand']); }
public final function execute() { $hasThreads = function_exists('pcntl_signal'); if (!$hasThreads || Cli::getInstance()->isSimulation()) { flush(); try { return $this->executeNoThread(); } catch (Interrupt $e) { throw $e; } catch (Exception $e) { echo $e; } return; } pcntl_signal(SIGCHLD, SIG_IGN); $pid = pcntl_fork(); if ($pid < 1) { $this->_run(); posix_kill(posix_getpid(), 9); pcntl_waitpid(posix_getpid(), $temp = 0, WNOHANG); pcntl_wifexited($temp); exit; //Make sure we exit... } else { $this->pid = $pid; } }
/** * Setting up and installing the data handler. * @param array $entries */ public function __construct($entries) { $this->entries = $entries; pcntl_signal_dispatch(); pcntl_signal(SIGTERM, array($this, 'signalHandler')); pcntl_signal(SIGCHLD, array($this, 'signalHandler')); }
/** * Start * * @param OutputInterface $output * * @return void */ protected function start(OutputInterface $output) { $output->writeln('Starting daemon...'); if (file_exists($this->pidfile)) { $output->writeln('<error>Daemon process is already running</error>'); return null; } $pid = pcntl_fork(); if ($pid == -1) { $output->writeln('<error>Could not fork</error>'); return null; } elseif ($pid) { file_put_contents($this->pidfile, $pid); $output->writeln('Daemon started with PID ' . $pid); } else { $terminated = false; pcntl_signal(SIGTERM, function ($signo) use(&$terminated) { if ($signo == SIGTERM) { $terminated = true; } }); while (!$terminated) { $this->executeOperation(); pcntl_signal_dispatch(); sleep(1); } $output->writeln('Daemon stopped'); } }
/** * constructor just initiates the default logger * which simply skips every log-message * **/ public function __construct() { $this->cloLogger = function ($strLogLine) { return; }; pcntl_signal(SIGCHLD, array($this, 'handleSIGCHLD')); }
function configure() { $this->pid = getmypid(); $this->mode = isset($_REQUEST['jaxl']) ? "cgi" : "cli"; if (!JAXLUtil::isWin() && JAXLUtil::pcntlEnabled() && $config['sigh'] != FALSE) { pcntl_signal(SIGTERM, array($this, "shutdown")); pcntl_signal(SIGINT, array($this, "shutdown")); JAXLog::log("Registering shutdown for SIGH Terms ...", 0, $this); } if (JAXLUtil::sslEnabled()) { JAXLog::log("Openssl enabled ...", 0, $this); } if ($this->mode == "cli") { if (!function_exists('fsockopen')) { die("Jaxl requires fsockopen method ..."); } file_put_contents(JAXL_PID_PATH, $this->pid); } if ($this->mode == "cgi") { if (!function_exists('curl_init')) { die("Jaxl requires curl_init method ..."); } } // include service discovery XEP, recommended for every IM client jaxl_require('JAXL0030', $this, array('category' => 'client', 'type' => 'bot', 'name' => JAXL_NAME, 'lang' => 'en')); }
public function registerSignalHandlers() { if (PHP_OS === 'Linux') { pcntl_signal(SIGTERM, array($this, 'signalHandler')); pcntl_signal(SIGINT, array($this, 'signalHandler')); } }
* $boris->onStart(function($worker, $vars){ * $worker->setLocal('date', date('Y-m-d')); * }); * * $boris->onStart('echo "The date is $date\n";'); */ public function onStart($hook) { $this->_startHooks[] = $hook; } /** * Add a new hook to run in the context of the REPL when a fatal error occurs. * * @param mixed $hook * * The hook is either a string of PHP code to eval(), or a Closure accepting * the EvalWorker object as its first argument and the array of defined * local variables in the second argument. * * If the hook is a callback and needs to set any local variables in the * REPL's scope, it should invoke $worker->setLocal($var_name, $value) to * do so. * * Hooks are guaranteed to run in the order they were added and the state * set by each hook is available to the next hook (either through global * resources, such as classes and interfaces, or through the 2nd parameter * of the callback, if any local variables were set. * * @example An example if your project requires some database connection cleanup: * * $boris->onFailure(function($worker, $vars){
protected function __construct() { set_error_handler('\\ManiaLive\\Application\\ErrorHandling::createExceptionFromError'); if (extension_loaded('pcntl')) { pcntl_signal(SIGTERM, array($this, 'kill')); pcntl_signal(SIGINT, array($this, 'kill')); declare (ticks=1); } try { $configFile = CommandLineInterpreter::preConfigLoad(); // load configuration file $loader = Loader::getInstance(); $loader->setConfigFilename(APP_ROOT . 'config' . DIRECTORY_SEPARATOR . $configFile); $loader->run(); // load configureation from the command line ... CommandLineInterpreter::postConfigLoad(); // add logfile prefix ... $manialiveConfig = \ManiaLive\Config\Config::getInstance(); $serverConfig = \ManiaLive\DedicatedApi\Config::getInstance(); if ($manialiveConfig->logsPrefix != null) { $manialiveConfig->logsPrefix = str_replace('%ip%', str_replace('.', '-', $serverConfig->host), $manialiveConfig->logsPrefix); $manialiveConfig->logsPrefix = str_replace('%port%', $serverConfig->port, $manialiveConfig->logsPrefix); } // disable logging? /*if(!$manialiveConfig->runtimeLog) \ManiaLive\Utilities\Logger::getLog('runtime')->disableLog();*/ } catch (\Exception $e) { // exception on startup ... ErrorHandling::processStartupException($e); } }
/** * Execute the console command. * * @return void */ public function fire() { $guard = App::make('guard'); $config = $guard->getConfig(); $realpaths = array(); $base = $config['base_path']; $paths = $config['paths']; $events = $config['events']; // tick use required as of PHP 4.3.0 declare (ticks=1); foreach ($this->signals as $signal) { pcntl_signal($signal, function ($signal) use($guard) { $guard->stop(); exit; }); } foreach ($paths as $path) { $realpath = realpath($base . '/' . $path); if ($realpath) { $realpaths[] = $realpath; } } $config['paths'] = $realpaths; $guard->setConfig($config); $this->line('Watcher started, waiting for changes...'); $guard->start(); }
function __construct($options) { $this->reset($options); pcntl_signal(SIGTERM, array("JAXLHTTPd", "shutdown")); pcntl_signal(SIGINT, array("JAXLHTTPd", "shutdown")); $options = getopt("p:b:"); foreach ($options as $opt => $val) { switch ($opt) { case 'p': $this->settings['port'] = $val; break; case 'b': $this->settings['maxq'] = $val; default: break; } } $this->httpd = socket_create(AF_INET, SOCK_STREAM, SOL_TCP); socket_set_option($this->httpd, SOL_SOCKET, SO_REUSEADDR, 1); socket_bind($this->httpd, 0, $this->settings['port']); socket_listen($this->httpd, $this->settings['maxq']); $this->id = $this->getResourceID($this->httpd); $this->clients = array("0#" . $this->settings['port'] => $this->httpd); echo "JAXLHTTPd listening on port " . $this->settings['port'] . PHP_EOL; }
/** * Init Tunnel. */ public function __construct() { $this->parentPID = getmypid(); $this->bridge = $this->createBridge(); $this->queue = msg_get_queue(ftok(__FILE__, 'k')); pcntl_signal(POLL_MSG, [$this, 'read']); }
/** * Executes the callback in a different thread. All arguments to this method will be passed on to the callback. * * The callback will be invoked but the script will not wait for it to finish. * @return null */ public function run() { $pid = @pcntl_fork(); if ($pid == -1) { throw new ZiboException('Could not run the thread: unable to fork the callback'); } if ($pid) { // parent process code $this->pid = $pid; } else { // child process code pcntl_signal(SIGTERM, array($this, 'signalHandler')); try { $this->callback->invokeWithArrayArguments(func_get_args()); } catch (Exception $exception) { $message = $exception->getMessage(); if (!$message) { $message = get_class($exception); } Zibo::getInstance()->runEvent(Zibo::EVENT_LOG, $message, $exception->getTraceAsString(), 1); echo $message . "\n"; echo $exception->getTraceAsString(); } exit; } }
public function start() { $this->_initialize(); // 检查是否需要启动 $this->_checkRunning(); // 后台daemon运行 Tool_Proc::daemonize(); // 设置运行账号 Tool_Proc::setUser($this->user); // daemon日志目录 Tool_Log::setSubDir($this->name); // 保存PID $this->_createPidFile(); // 重定向输出, 否则当终端退出后, 若还往标准输出写会导致php退出 $this->_setOutput(); // 不限制执行时间 set_time_limit(0); // 信号设置 pcntl_signal(SIGCHLD, SIG_IGN); pcntl_signal(SIGPIPE, SIG_IGN); // fork并运行子进程 for ($i = 0; $i < $this->childNum; $i++) { $this->_spawnChild($i); } // 运行主进程循环 $this->_mainLoop(); }
function __construct() { pcntl_signal(SIGINT, array($this, 'cleanShutdown')); pcntl_signal(SIGTERM, array($this, 'cleanShutdown')); $this->initBot(); while (true) { if (empty($this->servers)) { echo 'No servers to read from - Qutting' . "\n"; break; } $this->time = time(); $this->triggerTimers(); $this->triggerJobs(); $check = false; foreach ($this->servers as $Server) { if (false !== ($data = $Server->tick())) { $check = true; if (is_array($data)) { unset($data['raw']); // TODO: Logging & stuff $this->triggerPlugins($data, $Server); $Server->doSendQueue(); } } } if (!$check) { usleep(20000); } } }
protected function execute(InputInterface $input, OutputInterface $output) { $this->input = $input; $this->output = $output; declare (ticks=1); register_shutdown_function(array($this, 'stopCommand')); set_error_handler(array($this, 'errorHandler')); if (function_exists("pcntl_signal")) { pcntl_signal(SIGTERM, [$this, 'stopCommand']); pcntl_signal(SIGINT, [$this, 'stopCommand']); } else { } $this->isDebug = $input->getArgument('isDebug'); $port = $input->getOption('port'); $chat = $this->container->get('app.chat.handler'); $chat->setIsDebug($this->isDebug); $messageManager = new MessageManager($chat); $messageManager->setIsDebug($this->isDebug); $server = IoServer::factory(new HttpServer(new WsServer($messageManager)), $port); if ($this->isDebug) { $redis = $this->container->get('snc_redis.default'); $server->loop->addPeriodicTimer(5, function () use($redis, $messageManager) { $memory = memory_get_usage(); echo "Send messages. Redis value: " . $redis->get('value') . "\r\n"; $info = array(); $info['message'] = "Redis value: " . $redis->get('value') . "; Memory: " . $memory; $info['type'] = 'message'; $info['from'] = 'me'; $messageManager->sendAll(json_encode($info)); }); } $this->logMessage("Start server."); $server->run(); $this->logMessage("Finish execute daemon."); }
public function start() { if ($this->workingPid()) { return; } if ($this->pidfile) { if (is_file($this->pidfile)) { unlink($this->pidfile); } file_put_contents($this->pidfile, $this->pid() . PHP_EOL); } try { foreach (get_class_methods($this) as $method) { if (0 === strpos($method, '__signal_')) { pcntl_signal(constant('SIG' . strtoupper(substr($method, strlen('__signal_')))), [$this, $method]); } } $this->log('start'); $this->main(); $this->log('done'); } catch (Stop $stop) { if ($message = $stop->getMessage()) { $this->log($message); } } catch (\Exception $e) { $this->error_log($e); } finally { if ($this->workingPid() === $this->pid()) { unlink($this->pidfile); } } }
public function indexAction() { declare (ticks=1); pcntl_signal(SIGTERM, array($this, "sig_handler")); $mongoDir = "/usr"; $debugOutput = false; $port = $this->_getParam('port'); if (!file_exists($mongoDir . '/bin/mongod')) { throw new PHPUnit_Framework_SkippedTestError('mongo daemon not found'); } $this->_dir = tempnam('/tmp', 'mongodata'); unlink($this->_dir); mkdir($this->_dir); $cmd = "{$mongoDir}/bin/mongod --port={$port} --dbpath={$this->_dir}"; $descriptorspec = array(); if ($debugOutput) { echo $cmd . "\n"; $descriptorspec = array(1 => STDOUT, 2 => STDOUT); } else { $descriptorspec = array(1 => array('pipe', 'w'), 2 => STDOUT); } $this->_proc = new Kwf_Util_Proc($cmd, $descriptorspec); sleep(60 * 15); $this->_proc->terminate(); $this->_proc->close(false); system("rm -r " . escapeshellarg($this->_dir)); exit; }
private function sleepUntilThereIsSomethingInteresting($timeLimit, $child) { pcntl_signal(SIGALRM, [$this, "alarm"], true); pcntl_alarm($timeLimit); pcntl_waitpid($child, $status); //pcntl_signal_dispatch(); }
/** * Register a signal handler. * * * @param int $signalNumber Signal number. * @param callable|int $handler The signal handler. * * @throws RuntimeException When can not register handler. */ protected function registerHandler($signalNumber, $handler) { if (pcntl_signal($signalNumber, $handler)) { return; } throw new RuntimeException('Could not define signal handler'); }
/** * Start the thread * * @throws RuntimeException */ public function execute() { $this->threadKey = 'thread_' . rand(1000, 9999) . rand(1000, 9999) . rand(1000, 9999) . rand(1000, 9999); if (($this->pid = pcntl_fork()) == -1) { throw new RuntimeException('Couldn\'t fork the process'); } if ($this->pid) { // Parent //pcntl_wait($status); //Protect against Zombie children } else { // Child. pcntl_signal(SIGTERM, array($this, 'signalHandler')); $args = func_get_args(); $callable = $this->callable; if (!is_string($callable)) { $callable = (array) $this->callable; } try { $return = call_user_func_array($callable, (array) $args); if (!is_null($return)) { $this->saveResult($return); } // Executed only in PHP 7, will not match in PHP 5.x } catch (\Throwable $t) { $this->saveResult($t); // Executed only in PHP 5. Remove when PHP 5.x is no longer necessary. } catch (\Exception $ex) { $this->saveResult($ex); } exit(0); } }
public function execute(array $matches, $rest, $url) { //Debug::setLogger(new STDOUTLogger()); $cfg = new Config(); $currencyMeta = $cfg->getCurrencyMeta(); $scanner = new BillScannerDriver(); $scanner->stop(); foreach ([SIGINT, SIGTERM] as $signal) { pcntl_signal($signal, function () use($scanner) { $scanner->stop(); }); } $oldState = []; $scanner->attachObserver('tick', function () { pcntl_signal_dispatch(); })->attachObserver('billInserted', function ($desc) use($currencyMeta, $scanner) { $denoms = $currencyMeta->getDenominations(); if ($desc['billIndex'] === 4) { $scanner->setBillRejected(true); echo "-=[ REJECTING BILL FROM CLI-DRIVER ]=-\n"; } echo 'Bill Inserted(' . $desc['billIndex'] . '): ', $currencyMeta->format($denoms[$desc['billIndex']]), ' (', $currencyMeta->getISOCode(), ")\n"; })->attachObserver('stateChanged', function ($desc) use(&$oldState) { foreach ($desc as $state => $value) { if (isset($oldState[$state]) && $oldState[$state] !== $value) { echo $state, ": ", $value ? 'true' : 'false', "\n"; } $oldState[$state] = $value; } })->attachObserver('driverStopped', function () { echo "Driver stopped\n"; })->run(); }
function registerSignal() { pcntl_signal(SIGUSR1, "communicate"); pcntl_signal(SIGINT, "communicate"); //子进程挂掉时的监听 pcntl_signal(SIGCHLD, "communicate"); }
function __construct($config) { if (extension_loaded("pcntl")) { //Add signal handlers to shut down the bot correctly if its getting killed pcntl_signal(SIGTERM, array($this, "signalHandler")); pcntl_signal(SIGINT, array($this, "signalHandler")); } else { //die("Please make sure the pcntl PHP extension is enabled.\n"); } $this->config = $config; $this->startTime = time(); $this->lastServerMessage = $this->startTime; ini_set("memory_limit", $this->config['memoryLimit'] . "M"); if ($config['verifySSL']) { $this->socket = stream_socket_client("" . $config['server'] . ":" . $config['port']) or die("Connection error!"); } else { $socketContext = stream_context_create(array("ssl" => array("verify_peer" => false, "verify_peer_name" => false))); $this->socket = stream_socket_client("" . $config['server'] . ":" . $config['port'], $errno, $errstr, 30, STREAM_CLIENT_CONNECT, $socketContext) or die("Connection error!"); } stream_set_blocking($this->socket, 0); stream_set_timeout($this->socket, 600); $this->login(); $this->loadPlugins(); $this->main($config); }
/** * Runs this CLI server * * @return void */ public function __invoke() { $parser = $this->getParser(); $logger = $this->getLogger($parser); try { $result = $parser->parse(); $logger->setVerbosity($result->options['verbose']); try { $server = $this->getServer($result->options, $result->args); $server->setLogger($logger); if (extension_loaded('pcntl')) { pcntl_signal(SIGTERM, array($server, 'handleSignal')); pcntl_signal(SIGINT, array($server, 'handleSignal')); } $server->run(); } catch (Net_Notifier_Exception $e) { $logger->log($e->getMessage() . PHP_EOL, Net_Notifier_Logger::VERBOSITY_ERRORS); exit(1); } } catch (Console_CommandLine_Exception $e) { $logger->log($e->getMessage() . PHP_EOL, Net_Notifier_Logger::VERBOSITY_ERRORS); exit(1); } catch (Exception $e) { $logger->log($e->getMessage() . PHP_EOL, Net_Notifier_Logger::VERBOSITY_ERRORS); $logger->log($e->getTraceAsString() . PHP_EOL, Net_Notifier_Logger::VERBOSITY_ERRORS); exit(1); } }
/** * @param \Symfony\Component\Console\Input\InputInterface $input * @param \Symfony\Component\Console\Output\OutputInterface $output * @return int|void */ protected function execute(InputInterface $input, OutputInterface $output) { declare (ticks=1); $this->output = $output; // Register shutdown function register_shutdown_function(array($this, 'stopCommand')); // Register SIGTERM/SIGINT catch if script is killed by user if (function_exists('pcntl_signal')) { pcntl_signal(SIGTERM, array($this, 'stopCommand')); pcntl_signal(SIGINT, array($this, 'stopCommand')); } else { $this->output->writeln('<options=bold>Note:</> The PHP function pcntl_signal isn\'t defined, which means you\'ll have to do some manual clean-up after using this command.'); $this->output->writeln('Remove the file \'app/Mage.php.rej\' and the line \'Mage::log($name, null, \'n98-magerun-events.log\');\' from app/Mage.php after you\'re done.'); } $this->detectMagento($output); if ($this->initMagento()) { $currentMagerunDir = dirname(__FILE__); $patch = $currentMagerunDir . '/0001-Added-logging-of-events.patch'; // Enable logging & apply patch shell_exec('cd ' . \Mage::getBaseDir() . ' && n98-magerun.phar dev:log --on --global && patch -p1 < ' . $patch); $output->writeln('Tailing events... '); // Listen to log file shell_exec('echo "" > ' . \Mage::getBaseDir() . '/var/log/n98-magerun-events.log'); $handle = popen('tail -f ' . \Mage::getBaseDir() . '/var/log/n98-magerun-events.log 2>&1', 'r'); while (!feof($handle)) { $buffer = fgets($handle); $output->write($buffer); flush(); } pclose($handle); } }
/** * Constructor * * @param AMQPQueue[] $queues * @param float $idleTimeout in seconds * @param int $waitTimeout in microseconds * @param callable $deliveryCallback, * @param callable|null $flushCallback, * @param callable|null $errorCallback * @throws Exception\InvalidArgumentException */ public function __construct(array $queues, $idleTimeout, $waitTimeout, callable $deliveryCallback, callable $flushCallback = null, callable $errorCallback = null) { Assertion::float($idleTimeout); Assertion::integer($waitTimeout); if (function_exists('pcntl_signal_dispatch')) { $this->usePcntlSignalDispatch = true; } if (function_exists('pcntl_signal')) { pcntl_signal(SIGTERM, [$this, 'shutdown']); pcntl_signal(SIGINT, [$this, 'shutdown']); pcntl_signal(SIGHUP, [$this, 'shutdown']); } if (empty($queues)) { throw new Exception\InvalidArgumentException('No queues given'); } $q = []; foreach ($queues as $queue) { if (!$queue instanceof AMQPQueue) { throw new Exception\InvalidArgumentException('Queue must be an instance of AMQPQueue, ' . is_object($queue) ? get_class($queue) : gettype($queue) . ' given'); } if (null === $this->blockSize) { $this->blockSize = $queue->getChannel()->getPrefetchCount(); } $q[] = $queue; } $this->idleTimeout = (double) $idleTimeout; $this->waitTimeout = (int) $waitTimeout; $this->queues = new InfiniteIterator(new ArrayIterator($q)); }