php sleep 中断原因,sleep()遇到系统中断信号

研究RabbitMQ消费脚本注册信号时候,发现的问题

执行了 sleep(2),发起ctrl + c信号,发现获取系统时间没有 +2s。

1ae865a11d1f3891e678eda274c97a51.png

构建测试代码

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值