php pcntl signal,PHP: pcntl_signal - Manual

If you have a script that needs certain sections to not be interrupted by a signal (especially SIGTERM or SIGINT), but want to make your script ready to process that signal ASAP, there's only one way to do it. Flag the script as having received the signal, and wait for your script to say its ready to process it.

Here's a sample script:

$allow_exit = true;  // are we permitting exit?

$force_exit = false; // do we need to exit?

declare(ticks = 1);

register_tick_function('check_exit');

pcntl_signal(SIGTERM, 'sig_handler');

pcntl_signal(SIGINT, 'sig_handler');

function sig_handler () {

global $allow_exit, $force_exit;

if ($allow_exit)

exit;

else

$force_exit = true;

}

function check_exit () {

global $allow_exit, $force_exit;

if ($force_exit && $allow_exit)

exit;

}

$allow_exit = false;

$i = 0;

while (++$i) {

echo "still going (${i})\n";

if ($i == 10)

$allow_exit = true;

sleep(2);

}

?>

You set $allow_exit to true at all times when it is perfectly acceptable that your script could exit without warning. In sections where you really need the script to continue running, you set $allow_exit to false. Any signals received while $allow_exit is false will not take effect until you set $allow_exit to true.

$allow_exit = true;

// unimportant stuff here. exiting will not harm anything

$allow_exit = false;

// really important stuff not to be interrupted

$allow_exit = true;

// more unimportant stuff. if signal was received during

// important processing above, script will exit here

?>

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值