how to check if exit is clean in a shutdown functi

2019-03-30 10:13发布

How can I test if exit is clean in a shutdown function in PHP?

By clean exit I mean that the script was not terminated due to an error.

4条回答
别忘想泡老子
2楼-- · 2019-03-30 11:09

Its a good question, for the moment I only have this idea: register a shutdown function like this:

function shutdown() {
    if (defined('END_REACHED') {
        echo 'Script executed with no error', PHP_EOL;
    }
}

register_shutdown_function('shutdown');

With auto_append_file add an additional file to the very end of every script execution which sets an constant.

Your auto_append_file.php content:

define('END_REACHED', TRUE);

In case you dont want to edit the php.ini you could do check error_get_last() or $php_errormsg in your register shutdown function!

查看更多
成全新的幸福
3楼-- · 2019-03-30 11:14

There are lots of reasons a script might terminate prematurely. There is no generic solution. The only errors which will cause the script to terminate prematurely are fatal errors - and in most cases a shutdown function will not run after a fatal error, similarly a custom error handler will only reliably see non-fatal errors. Then there's the option of setting up signal handlers - but again they only see some of the story.

The big question of course, is what do you want to do with this information in the shutdown function?

The only reliable way to determine of your logic completed as expected is to raise a semaphore when this happens and check it in the shutdown function.

查看更多
Bombasti
4楼-- · 2019-03-30 11:14

I've ported (for PHP 5.3) ezcExecution component which handles this nicely. See https://github.com/sobstel/Execution. Basically you need to inform lib that exit was clean (by calling Execution::cleanExit(). Otherwise it means exit was not clean. Simple like that.

查看更多
叛逆
5楼-- · 2019-03-30 11:15

A call to error_get_last() can tell you if or which error occurred. If the function returns NULL, it is a clean shutdown.

查看更多
登录 后发表回答