首页 > 解决方案 > Call function to exit gracefully when script timeout reached

问题描述

I have a PHP script running through CLI on PHP 5.5 & PHP 7 which is called by Nagios, upon the timeout Nagios runs a very unfriendly kill -9 on the script.

So I want to the user to be able to specify a timeout on the command line (which I grab using getopt) to start a timer, then for the script to continue as normal.

The result should be:

  1. The script is running too long and a function is called to quit the script and stop any outstanding operations (like a PDO DB query is taking too long as an example)
  2. The script completes before the timeout, the script quits as normal and the timer is cancelled

The timer should be for the entire script not just a single function call (give or take a few microseconds to set the timer up which is fine)

It seems something really simple, but I cannot seem to find a way to do it, all the information I can find is around setting the execution timeout after which the script quits with no control so I cannot message Nagios back that there was a timeout.

Any ideas? Thanks.

标签: phpnagios

解决方案


嗯,好吧,看来我能想到的唯一方法就是这样(任何改进建议都会很棒)

在 Linux 下调用脚本

超时 --signal=SIGHUP 120s script.php ....

在 PHP 脚本里面放这个:

// Protect from some causes of death
function sig_handler($sig) {
    echo "UNKNOWN, Script Dying: I was killed before the requested work could be completed.  (Execution Time " .
        round((microtime() - $GLOBALS['timer']),2) . " secs)" . PHP_EOL;
    exit (3);
}

// Start Timer
$timer = microtime(true);

// Catch Signals
pcntl_signal(SIGINT,  "sig_handler");
pcntl_signal(SIGTERM, "sig_handler");
pcntl_signal(SIGHUP,  "sig_handler");

显然计时器是可选的


推荐阅读