研究RabbitMQ消费脚本注册信号时候,发现的问题
执行了 sleep(2)
,发起ctrl + c
信号,发现获取系统时间没有 +2s。
构建测试代码
<?php
namespace App\Console\Commands;
use Illuminate\Console\Command;
class TestSignal extends Command
{
protected $signature = 'test:signal';
public function handle()
{
pcntl_async_signals(true);
$interrupted = false;
pcntl_signal(SIGINT, function ($signal) use (&$interrupted) {
$interrupted = true;
echo (sprintf('got signal[%d]', $signal)) . "\n";
});
while (!$interrupted) {
echo "sleep 3s\n";
sleep(3);
echo "current time: " .date('Y-m-d H:i:s') . "\n";
}
}
}
验证效果
使用 phptrace -p pid
查看运行时的函数调用信息
...
> sleep(3)
< sleep(3) = 0
> date("Y-m-d H:i:s")
< date("Y-m-d H:i:s") = "2018-12-13 18:04:05"
> sleep(3)
< sleep(3) = 0
> date("Y-m-d H:i:s")
< date("Y-m-d H:i:s") = "2018-12-13 18:04:08"
> sleep(3)
< sleep(3) = 3
> App\Console\Commands\TestSignal->App\Console\Commands\{closure}(2, array(3))
> sprintf("got signal[%d]", 2)
< sprintf("got signal[%d]", 2) = "got signal[2]"
< App\Console\Commands\TestSignal->App\Console\Commands\{closure}(2, array(3)) = NULL
> date("Y-m-d H:i:s")
< date("Y-m-d H:i:s") = "2018-12-13 18:04:08"
...
当执行ctrl + c
时,sleep(3) 会直接返回,所以获取当前时间又是 2018-12-13 18:04:08
。
官网解释
If the call was interrupted by a signal, sleep() returns a non-zero value.
On Windows, this value will always be 192 (the value of the WAIT_IO_COMPLETION constant within the Windows API).
On other platforms, the return value will be the number of seconds left to sleep.