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

论坛 期权论坛 编程之家     
选择匿名的用户   2021-6-2 21:04   6876   0

研究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 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:3875789
帖子:775174
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP