本文整理汇总了PHP中pcntl_alarm函数的典型用法代码示例。如果您正苦于以下问题:PHP pcntl_alarm函数的具体用法?PHP pcntl_alarm怎么用?PHP pcntl_alarm使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了pcntl_alarm函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的PHP代码示例。
示例1: minecraft_command
function minecraft_command($signal)
{
global $_CONFIG, $_STATE;
switch ($signal) {
case SIGHUP:
logmsg("SIGHUP - reload");
$command = 'reload';
break;
case SIGUSR1:
logmsg("SIGUSR1 - save-on");
$command = 'save-on';
break;
case SIGUSR2:
logmsg("SIGUSR2 - save-off");
$command = 'save-off';
break;
case SIGALRM:
logmsg("SIGALRM - save-all");
$command = 'save-all';
if (isset($_CONFIG['AlarmInterval'])) {
pcntl_alarm($_CONFIG['AlarmInterval']);
}
break;
}
fwrite($_STATE['Descriptors'][0], $command . PHP_EOL);
fflush($_STATE['Descriptors'][0]);
}
开发者ID:haxney,项目名称:minecraft-config,代码行数:27,代码来源:daemonize_minecraft.php
示例2: sleepUntilThereIsSomethingInteresting
private function sleepUntilThereIsSomethingInteresting($timeLimit, $child)
{
pcntl_signal(SIGALRM, [$this, "alarm"], true);
pcntl_alarm($timeLimit);
pcntl_waitpid($child, $status);
//pcntl_signal_dispatch();
}
开发者ID:onebip,项目名称:onebip-concurrency,代码行数:7,代码来源:Poison.php
示例3: beat
public function beat()
{
if (false === $this->stopped) {
pcntl_alarm((int) 1);
$this->tick();
}
}
开发者ID:romainneutron,项目名称:Tip-Top,代码行数:7,代码来源:Pulse.php
示例4: signalHandler
/**
* Signal handler
*
* @param int $signalNumber
* @return void
*/
public function signalHandler($signalNumber)
{
echo 'Handling signal: #' . $signalNumber . PHP_EOL;
global $consumer;
switch ($signalNumber) {
case SIGTERM:
// 15 : supervisor default stop
// 15 : supervisor default stop
case SIGQUIT:
// 3 : kill -s QUIT
$consumer->stopHard();
break;
case SIGINT:
// 2 : ctrl+c
$consumer->stop();
break;
case SIGHUP:
// 1 : kill -s HUP
$consumer->restart();
break;
case SIGUSR1:
// 10 : kill -s USR1
// send an alarm in 1 second
pcntl_alarm(1);
break;
case SIGUSR2:
// 12 : kill -s USR2
// send an alarm in 10 seconds
pcntl_alarm(10);
break;
default:
break;
}
return;
}
开发者ID:CarsonF,项目名称:php-amqplib,代码行数:41,代码来源:amqp_consumer_signals.php
示例5: setSigAlarm
protected function setSigAlarm()
{
pcntl_signal(SIGALRM, array(&$this, 'sigAlarmCallback'));
$sec = $this->getSigAlarmTimeout();
if ($sec > -1) {
pcntl_alarm($this->getSigAlarmTimeout());
}
}
开发者ID:ketheriel,项目名称:ETVA,代码行数:8,代码来源:etvaBaseTask.class.php
示例6: setupDaemon
/**
* Loads to configuration from the daemon options and installs signal
* handlers.
*
* @param DaemonOptions $daemonOptions
*/
private function setupDaemon(DaemonOptions $daemonOptions)
{
$this->requestCount = 0;
$this->requestLimit = $daemonOptions->getOption(DaemonOptions::REQUEST_LIMIT);
$this->memoryLimit = $daemonOptions->getOption(DaemonOptions::MEMORY_LIMIT);
$timeLimit = $daemonOptions->getOption(DaemonOptions::TIME_LIMIT);
if (DaemonOptions::NO_LIMIT !== $timeLimit) {
pcntl_alarm($timeLimit);
}
$this->installSignalHandlers();
}
开发者ID:sojimaxi,项目名称:FastCGIDaemon,代码行数:17,代码来源:DaemonTrait.php
示例7: testStreamSelectSignalInterrupt
/**
* Test stream_select signal interrupt doesn't trigger \RunTime exception.
*/
public function testStreamSelectSignalInterrupt()
{
$address = 'tcp://localhost:7000';
$serverSocket = stream_socket_server($address);
$connectionPool = new StreamSocketConnectionPool($serverSocket);
$alarmCalled = false;
declare (ticks=1);
pcntl_signal(SIGALRM, function () use(&$alarmCalled) {
$alarmCalled = true;
});
pcntl_alarm(1);
$connectionPool->getReadableConnections(2);
$this->assertTrue($alarmCalled);
}
开发者ID:sojimaxi,项目名称:FastCGIDaemon,代码行数:17,代码来源:StreamSocketConnectionPoolTest.php
示例8: setUp
public function setUp()
{
// Make this process a session leader so we can send signals
// to this job as a whole (including any subprocesses such as spawned by Symfony).
posix_setsid();
if (function_exists('pcntl_alarm') && function_exists('pcntl_signal')) {
if (!empty($this->args['sigFile'])) {
echo sprintf('[-] Signal file requested, polling "%s".' . PHP_EOL, $this->args['sigFile']);
declare (ticks=1);
pcntl_signal(SIGALRM, [$this, 'alarmHandler']);
pcntl_alarm(1);
}
}
$this->updateStatus(DNDeployment::TR_DEPLOY);
chdir(BASE_PATH);
}
开发者ID:silverstripe,项目名称:deploynaut,代码行数:16,代码来源:DeployJob.php
示例9: pleac_Timing_Out_an_Operation
function pleac_Timing_Out_an_Operation()
{
declare (ticks=1);
$aborted = false;
function handle_alarm($signal)
{
global $aborted;
$aborted = true;
}
pcntl_signal(SIGALRM, 'handle_alarm');
pcntl_alarm(3600);
// long-time operations here
pcntl_alarm(0);
if ($aborted) {
// timed out - do what you will here
}
}
开发者ID:Halfnhav4,项目名称:pfff,代码行数:17,代码来源:Timing_Out_an_Operation.php
示例10: invoke
/**
* Invokes a callable and raises an exception when the execution does not
* finish before the specified timeout.
*
* @param callable $callable
* @param array $arguments
* @param int $timeout in seconds
* @return mixed
* @throws InvalidArgumentException
*/
public function invoke($callable, array $arguments, $timeout)
{
if (!is_callable($callable)) {
throw new InvalidArgumentException();
}
if (!is_integer($timeout)) {
throw new InvalidArgumentException();
}
pcntl_signal(SIGALRM, array($this, 'callback'), TRUE);
pcntl_alarm($timeout);
$this->timeout = $timeout;
try {
$result = call_user_func_array($callable, $arguments);
} catch (Exception $e) {
pcntl_alarm(0);
throw $e;
}
pcntl_alarm(0);
return $result;
}
开发者ID:AndyDune,项目名称:rzn.phpunit4,代码行数:30,代码来源:Invoker.php
示例11: run
/**
* Executes a callable until a timeout is reached or the callable returns `true`.
*
* @param Callable $callable The callable to execute.
* @param integer $timeout The timeout value.
* @return mixed
*/
public static function run($callable, $timeout = 0)
{
if (!is_callable($callable)) {
throw new InvalidArgumentException();
}
$timeout = (int) $timeout;
if (!function_exists('pcntl_signal')) {
throw new Exception("PCNTL threading is not supported on your OS.");
}
pcntl_signal(SIGALRM, function ($signal) use($timeout) {
throw new TimeoutException("Timeout reached, execution aborted after {$timeout} second(s).");
}, true);
pcntl_alarm($timeout);
$result = null;
try {
$result = $callable();
} catch (Exception $e) {
throw $e;
} finally {
pcntl_alarm(0);
}
return $result;
}
开发者ID:crysalead,项目名称:code,代码行数:30,代码来源:Code.php
示例12: add
/**
*
* 添加一个任务
*
* @param int $time_long 多长时间运行一次 单位秒
* @param callback $func 任务运行的函数或方法
* @param mix $args 任务运行的函数或方法使用的参数
* @return void
*/
public static function add($time_long, $func, $args = array(), $persistent = true)
{
if ($time_long <= 0) {
return false;
}
if (!is_callable($func)) {
if (class_exists('\\Man\\Core\\Lib\\Log')) {
\Man\Core\Lib\Log::add(var_export($func, true) . "not callable\n");
}
return false;
}
// 有任务时才出发计时器
if (empty(self::$tasks)) {
pcntl_alarm(1);
}
$time_now = time();
$run_time = $time_now + $time_long;
if (!isset(self::$tasks[$run_time])) {
self::$tasks[$run_time] = array();
}
self::$tasks[$run_time][] = array($func, $args, $persistent, $time_long);
return true;
}
开发者ID:walkor,项目名称:workerman-bench,代码行数:32,代码来源:Task.php
示例13: run
/**
* 运行守护进程,监控有变化的日志文件。
*
* @see ZtChart_Model_Monitor_Abstract::daemon()
*/
public function run()
{
if (0 == ($pid = pcntl_fork())) {
// 子进程负责处理当前日志
try {
$this->tail($this->_console->getLogPaths());
} catch (ZtChart_Model_Monitor_Exception $e) {
$this->_logger->err($e->getMessage());
exit(1);
}
} else {
if (0 < $pid) {
pcntl_setpriority(-1);
// 父进程负责把子进产生的数据写入数据库
if (pcntl_sigprocmask(SIG_BLOCK, array(SIGCHLD, SIGALRM, SIGINT, SIGTERM))) {
$interval = 10;
// 10秒写一次
pcntl_alarm($interval);
while ($signo = pcntl_sigwaitinfo(array(SIGCHLD, SIGALRM, SIGINT, SIGTERM))) {
if (SIGALRM == $signo) {
pcntl_alarm($interval);
}
try {
$this->extract($interval);
} catch (ZtChart_Model_Monitor_Exception $e) {
posix_kill($pid, 9);
exit(1);
}
if (SIGCHLD == $signo || SIGINT == $signo || SIGTERM == $signo) {
break;
}
}
}
}
}
exit(0);
}
开发者ID:starflash,项目名称:ZtChart-ZF1-Example,代码行数:42,代码来源:Realtime.php
示例14: delAll
/**
* Remove all timers.
* @return void
*/
public static function delAll()
{
self::$_tasks = array();
pcntl_alarm(0);
if (self::$_event) {
self::$_event->clearAllTimer();
}
}
开发者ID:TongJiankang,项目名称:Workerman,代码行数:12,代码来源:Timer.php
示例15: recvInnerTcp
/**
* 处理内部通讯收到的数据
* @param event_buffer $event_buffer
* @param int $fd
* @return void
*/
public function recvInnerTcp($connection, $flag, $fd = null)
{
$this->currentDealFd = $fd;
$buffer = stream_socket_recvfrom($connection, $this->recvBuffers[$fd]['remain_len']);
// 出错了
if ('' == $buffer && '' == ($buffer = fread($connection, $this->recvBuffers[$fd]['remain_len']))) {
// 判断是否是链接断开
if (!feof($connection)) {
return;
}
// 如果该链接对应的buffer有数据,说明发生错误
if (!empty($this->recvBuffers[$fd]['buf'])) {
$this->statusInfo['send_fail']++;
}
// 关闭链接
$this->closeInnerClient($fd);
$this->notice("CLIENT:" . $this->getRemoteIp() . " CLOSE INNER_CONNECTION\n");
if ($this->workerStatus == self::STATUS_SHUTDOWN) {
$this->stop();
}
return;
}
$this->recvBuffers[$fd]['buf'] .= $buffer;
$remain_len = $this->dealInnerInput($this->recvBuffers[$fd]['buf']);
// 包接收完毕
if (0 === $remain_len) {
// 内部通讯业务处理
$this->innerDealProcess($this->recvBuffers[$fd]['buf']);
$this->recvBuffers[$fd] = array('buf' => '', 'remain_len' => GatewayProtocol::HEAD_LEN);
} else {
if (false === $remain_len) {
// 出错
$this->statusInfo['packet_err']++;
$this->notice("INNER_PACKET_ERROR and CLOSE_INNER_CONNECTION\nCLIENT_IP:" . $this->getRemoteIp() . "\nBUFFER:[" . bin2hex($this->recvBuffers[$fd]['buf']) . "]\n");
$this->closeInnerClient($fd);
} else {
$this->recvBuffers[$fd]['remain_len'] = $remain_len;
}
}
// 检查是否是关闭状态或者是否到达请求上限
if ($this->workerStatus == self::STATUS_SHUTDOWN) {
// 停止服务
$this->stop();
// EXIT_WAIT_TIME秒后退出进程
pcntl_alarm(self::EXIT_WAIT_TIME);
}
}
开发者ID:shitfSign,项目名称:workerman-MT,代码行数:53,代码来源:Gateway.php
示例16: testSeeding
/**
* Test seeding
*
* @return void
*/
public function testSeeding()
{
$this->torrent_file = $this->createTorrentFile();
$this->download_destination = $this->createDownloadDestination();
$this->seed_server_pid = $this->startSeedServer();
$this->torrent_client_pid = $this->startTorrentClient();
// We don't want to wait forever.
$self = $this;
pcntl_signal(SIGALRM, function () use($self) {
$self->fail('Test timed out.');
});
pcntl_alarm(self::TEST_TIMEOUT);
$pid_exit = pcntl_wait($status);
switch ($pid_exit) {
case -1:
$this->fail('Error in child processes.');
break;
case $this->seed_server_pid:
unset($this->seed_server_pid);
$this->fail('Seed server exited.');
break;
case $this->torrent_client_pid:
unset($this->torrent_client_pid);
break;
}
$download_path = $this->download_destination . '/' . self::FILE_TO_DOWNLOAD;
$this->assertFileExists($download_path);
$downloaded_hash = sha1_file($download_path);
$expected_hash = sha1_file(dirname(__FILE__) . '/../Fixtures/' . self::FILE_TO_DOWNLOAD);
$this->assertEquals($expected_hash, $downloaded_hash);
}
开发者ID:StealThisShow,项目名称:StealThisTracker,代码行数:36,代码来源:SeedServerTest.php
示例17: forExactly
public function forExactly($duration)
{
// what are we doing?
$log = usingLog()->startAction("run for exactly '{$duration}'");
// remember the duration
//
// the $action callback can then make use of it
$this->duration = $duration;
// convert the duration into seconds
$interval = new DateInterval($duration);
$seconds = $interval->getTotalSeconds();
// set the alarm
pcntl_signal(SIGALRM, array($this, "handleSigAlarm"), FALSE);
$log->addStep("setting SIGALRM for '{$seconds}' seconds", function () use($seconds) {
pcntl_alarm($seconds);
});
declare (ticks=1);
$callback = $this->action;
$returnVal = $callback($this);
// all done
$log->endAction();
return $returnVal;
}
开发者ID:datasift,项目名称:storyplayer,代码行数:23,代码来源:TimedAction.php
示例18: masterSignalHandler
/**
* Обработка сигналов Мастером.
*
* @param int $signo Код сигнала
* @param mixed $pid Идентификатор процесса для обработки
* @param mixed $status Статус завершения процесса
* @throws \Ganzal\Lulz\Pinger\Assets\Exceptions\Master_Bad_Signal_Exception
* @return void
* @access protected
* @static
*/
protected static function masterSignalHandler($signo, $pid = null, $status = null)
{
DEBUG && printf("Master::masterSignalHandler(%s, %s, %s): begin\n", var_export($signo, true), var_export($pid, true), var_export($status, true));
switch ($signo) {
case SIGHUP:
case SIGINT:
case SIGQUIT:
case SIGTERM:
case SIGABRT:
DEBUG && (print "Master::masterSignalHandler(): master_loop = false\n");
static::$master_loop = false;
pcntl_signal_dispatch();
break;
case SIGALRM:
case SIGCHLD:
case SIGCLD:
// Пид не указан - сигнал от системы. Уточняем кто умер.
if (!$pid) {
$pid = pcntl_waitpid(-1, $status, WNOHANG);
}
// Дожидаемся окончания очереди умерших.
while ($pid > 0) {
if ($pid && isset(static::$jobs[$pid])) {
DEBUG && (print "Master::masterSignalHandler(): ((**))\n");
$exitCode = pcntl_wexitstatus($status);
if ($exitCode != 0) {
DEBUG && printf("Master::masterSignalHandler(): %d exited with status %d\n", $pid, $exitCode);
}
// этот демон не требует возврата слотов в пул
//array_push(static::$pid_slots, static::$jobs[$pid]);
// удаление завершенного процесса из списка
unset(static::$jobs[$pid]);
} elseif ($pid) {
DEBUG && (print "Master::masterSignalHandler(): (())\n");
// пид указан, но не в нашем списке детишек!
// запишем в очередь сигналов, вдруг чо
DEBUG && printf("Master::masterSignalHandler(): adding %d to the signal queue \n", $pid);
static::$sig_queue[$pid] = $status;
}
$pid = pcntl_waitpid(-1, $status, WNOHANG);
}
pcntl_alarm(10);
break;
default:
throw new Exceptions\Master_Bad_Signal_Exception($signo);
}
// switch($signo)
DEBUG && (print "Master::masterSignalHandler(): end\n\n");
}
开发者ID:Ganzal,项目名称:php-pinger-service,代码行数:60,代码来源:Master.php
示例19: registerTimeoutHandler
/**
* Register the worker timeout handler (PHP 7.1+).
*
* @param \Illuminate\Contracts\Queue\Job|null $job
* @param WorkerOptions $options
* @return void
*/
protected function registerTimeoutHandler($job, WorkerOptions $options)
{
if (version_compare(PHP_VERSION, '7.1.0') < 0 || !extension_loaded('pcntl')) {
return;
}
$timeout = $job && !is_null($job->timeout()) ? $job->timeout() : $options->timeout;
pcntl_async_signals(true);
pcntl_signal(SIGALRM, function () {
$this->exceptions->report(new TimeoutException('A queue worker timed out while processing a job.'));
exit(1);
});
pcntl_alarm($timeout + $options->sleep);
}
开发者ID:bryanashley,项目名称:framework,代码行数:20,代码来源:Worker.php
示例20: dealInputBase
/**
* 处理受到的数据
* @param event_buffer $event_buffer
* @param int $fd
* @return void
*/
public function dealInputBase($connection, $length, $buffer, $fd = null)
{
$this->currentDealFd = $fd;
// 出错了
if ($length == 0) {
if (feof($connection)) {
// 客户端提前断开链接
$this->statusInfo['client_close']++;
} else {
// 超时了
$this->statusInfo['recv_timeout']++;
}
$this->closeClient($fd);
if ($this->workerStatus == self::STATUS_SHUTDOWN) {
$this->stopServe();
}
return;
}
if (isset($this->recvBuffers[$fd])) {
$buffer = $this->recvBuffers[$fd] . $buffer;
}
$remain_len = $this->dealInput($buffer);
// 包接收完毕
if (0 === $remain_len) {
// 逻辑超时处理,逻辑只能执行xxs,xxs后超时放弃当前请求处理下一个请求
pcntl_alarm(ceil($this->processTimeout / 1000));
// 执行处理
try {
declare (ticks=1);
// 业务处理
$this->dealProcess($buffer);
// 关闭闹钟
pcntl_alarm(0);
} catch (Exception $e) {
// 关闭闹钟
pcntl_alarm(0);
if ($e->getCode() != self::CODE_PROCESS_TIMEOUT) {
$this->notice($e->getMessage() . ":\n" . $e->getTraceAsString());
$this->statusInfo['throw_exception']++;
$this->sendToClient($e->getMessage());
}
}
// 是否是长连接
if ($this->isPersistentConnection) {
// 清空缓冲buffer
unset($this->recvBuffers[$fd]);
} else {
// 关闭链接
$this->closeClient($fd);
}
} else {
if (false === $remain_len) {
// 出错
$this->statusInfo['packet_err']++;
$this->sendToClient('packet_err:' . $buffer);
$this->notice('packet_err:' . $buffer);
$this->closeClient($fd);
} else {
$this->recvBuffers[$fd] = $buffer;
}
}
// 检查是否到达请求上限或者服务是否是关闭状态
if ($this->statusInfo['total_request'] >= $this->maxRequests || $this->workerStatus == self::STATUS_SHUTDOWN) {
// 停止服务
$this->stopServe();
// 5秒后退出进程
pcntl_alarm(self::EXIT_WAIT_TIME);
}
}
开发者ID:nangong92t,项目名称:go_src,代码行数:75,代码来源:PHPServerWorker.php
注:本文中的pcntl_alarm函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论