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 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?
  • ¥15 关于#vue.js#的问题:修改用户信息功能图片无法回显,数据库中只存了一张图片(相关搜索:字符串)
  • ¥15 texstudio的问题,