gpt4 book ai didi

PHP register_shutdown_function 在脚本从命令行被杀死时触发?

转载 作者:可可西里 更新时间:2023-10-31 22:12:13 27 4
gpt4 key购买 nike

当从命令行(通过 Ctrl+c)或使用 kill 命令终止 cron 进程时,是否可以调用函数?

我已经尝试过register_shutdown_function(),但它似乎并没有在脚本被杀死时被调用,而是在脚本正常结束时被调用。

我正在尝试将结果记录到文件中,并在 cron 实例自动终止(即运行时间过长)时更新数据库值。

最佳答案

根据 comment in the manual on register_shutdown_function() ,这可以通过以下方式完成:

When using CLI ( and perhaps command line without CLI - I didn't test it) the shutdown function doesn't get called if the process gets a SIGINT or SIGTERM. only the natural exit of PHP calls the shutdown function. To overcome the problem compile the command line interpreter with --enable-pcntl and add this code:

 <?php
declare(ticks = 1); // enable signal handling
function sigint() {
exit;
}
pcntl_signal(SIGINT, 'sigint');
pcntl_signal(SIGTERM, 'sigint');
?>

This way when the process recieves one of those signals, it quits normaly, and the shutdown function gets called. ... (abbreviating to save space, read the full text)

如果这太麻烦,我会考虑通过设置时间限制从 PHP 内部进行超时。达到限制会抛出 fatal error ,关闭函数应该会被正常调用。

关于PHP register_shutdown_function 在脚本从命令行被杀死时触发?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3909798/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com