php cli模式 执行中断,php – 在CLI上的脚本中止后执行代码

函数

pcntl_signal()是使用Ctrl-C(以及其他信号)中断脚本时的情况的答案.你必须注意文档.它说:

You must use the declare() statement to specify the locations in your program where callbacks are allowed to occur for the signal handler to function properly.

除其他事项外,declare()语句安装一个回调函数,通过调用函数pcntl_signal_dispatch()来处理自上次调用以来接收到的信号的调度,函数pcntl_signal_dispatch()又调用您安装的信号处理程序.

或者,当您认为它适合您的代码流时,您可以自己调用函数pcntl_signal_dispatch()(并且根本不使用declare(ticks = 1)).

这是一个使用declare(ticks = 1)的示例程序:

declare(ticks=1);

// Install the signal handlers

pcntl_signal(SIGHUP, 'handleSigHup');

pcntl_signal(SIGINT, 'handleSigInt');

pcntl_signal(SIGTERM, 'handleSigTerm');

while(true) {

echo 'loop';

sleep(1);

}

// Reset the signal handlers

pcntl_signal(SIGHUP, SIG_DFL);

pcntl_signal(SIGINT, SIG_DFL);

pcntl_signal(SIGTERM, SIG_DFL);

/**

* SIGHUP: the controlling pseudo or virtual terminal has been closed

*/

function handleSigHup()

{

echo("Caught SIGHUP, terminating.\n");

exit(1);

}

/**

* SIGINT: the user wishes to interrupt the process; this is typically initiated by pressing Control-C

*

* It should be noted that SIGINT is nearly identical to SIGTERM.

*/

function handleSigInt()

{

echo("Caught SIGINT, terminating.\n");

exit(1);

}

/**

* SIGTERM: request process termination

*

* The SIGTERM signal is a generic signal used to cause program termination.

* It is the normal way to politely ask a program to terminate.

* The shell command kill generates SIGTERM by default.

*/

function handleSigTerm()

{

echo("Caught SIGTERM, terminating.\n");

exit(1);

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值