dongzhi4470 2015-11-27 10:35
浏览 77
已采纳

如何在php-fpm / nginx上停止php脚本执行?

Unfortunately calling php exit() on php-fpm/nginx configuration does not stop the script immediately while file handles might not be closed.

Some developers suggest calling fastcgi_finish_request() but also this does not stop the script.

Others suggest wrapping all code in a catch block:

<?php
    class SystemExit extends Exception {}
    try {
       /* PUT ALL THE CODE HERE */
    } catch (SystemExit $e) { /* do nothing */ }
?>

and throwing an exception where code stop is needed:

if (SOME_EXIT_CONDITION)
   throw new SystemExit(); // instead of exit()

This would mean editing all php files to include try/catch block and seems tedious to me.

Are there any other clean solutions?

  • 写回答

1条回答 默认 最新

  • drbd65446 2015-11-27 11:33
    关注

    So we found out that it's a register_shutdown_function callback that prevents your script from exiting immediately.

    PHP shutdown function is designed to be called on any script shutdown when possible. But it has a feature: if one of shutdown callbacks calls exit — script is exiting without calling any other callbacks.

    So if you really want to skip a shutdown function in some cases, you should register some killer-function as a very first shutdown callback. Inside that killer-function you will check a kind of singleton for state: do we want to exit? — call exit(), otherwise — return.

    <?php
    
    function killer_function() {
        if ($someGlobalThing->needToExitRightNow()) {
            exit();
        }
    }
    
    register_shutdown_function('killer_function');
    
    // ...
    
    function exit_now() {
        $someGlobalThing->exitNow();
        exit();
    }
    

    ($someGlobalThing can be a singleton or some super-global variable or a global registry or whatever you like)

    Then calling exit_now() will do the trick.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 小程序中fit格式等运动数据文件怎样实现可视化?(包含心率信息))
  • ¥15 如何利用mmdetection3d中的get_flops.py文件计算fcos3d方法的flops?
  • ¥40 串口调试助手打开串口后,keil5的代码就停止了
  • ¥15 电脑最近经常蓝屏,求大家看看哪的问题
  • ¥60 高价有偿求java辅导。工程量较大,价格你定,联系确定辅导后将采纳你的答案。希望能给出完整详细代码,并能解释回答我关于代码的疑问疑问,代码要求如下,联系我会发文档
  • ¥50 C++五子棋AI程序编写
  • ¥30 求安卓设备利用一个typeC接口,同时实现向pc一边投屏一边上传数据的解决方案。
  • ¥15 SQL Server analysis services 服务安装失败
  • ¥15 基于面向对象的图书馆借阅管理系统
  • ¥15 opencv图像处理,需要四个处理结果图