PHP CLI脚本可以在脚本停止时检测/触发回调吗?

时间:2014-07-18 15:32:12

标签: php command-line-interface

PHP CLI脚本是否可以检测它是否即将被停止?这应该适用于使用 Ctrl + C 退出脚本,或脚本是否自然结束。理想情况下,在脚本完全停止之前,我正在寻找某种类型的回调函数。

我原本以为我可以使用__destruct()函数创建一个类,如下所示:

<?php

class ExitHandler {
    public function __destruct() {
        toOut('Script Halted'); // Writes to STDOUT
    }
}

$exitHandler = new ExitHandler();

// ...

?>

然而,虽然测试显示当脚本自然退出时会触发,但如果脚本被 Ctrl + C 暂停,则不会触发:

php -r "Class Abc { public function __destruct() { echo 'Bye.'; } } $x = new Abc();"
=>Bye.

php -r "Class Abc { public function __destruct() { echo 'Bye.'; } } $x = new Abc(); while(true) { sleep(1); fwrite(STDOUT, 'Tick'); }"
=>TickTickTick^C

1 个答案:

答案 0 :(得分:2)

我相信pcntl_signal将允许您处理常规(非杀死-9)关闭

从上面的链接中取得的例子:

<?php
// tick use required as of PHP 4.3.0
declare(ticks = 1);

// signal handler function
function sig_handler($signo)
{

     switch ($signo) {
         case SIGTERM:
             // handle shutdown tasks
             exit;
             break;
         case SIGHUP:
             // handle restart tasks
             break;
         case SIGUSR1:
             echo "Caught SIGUSR1...\n";
             break;
         default:
             // handle all other signals
     }

}

echo "Installing signal handler...\n";

// setup signal handlers
pcntl_signal(SIGTERM, "sig_handler");
pcntl_signal(SIGHUP,  "sig_handler");
pcntl_signal(SIGUSR1, "sig_handler");

// or use an object, available as of PHP 4.3.0
// pcntl_signal(SIGUSR1, array($obj, "do_something"));

echo"Generating signal SIGTERM to self...\n";

// send SIGUSR1 to current process id
posix_kill(posix_getpid(), SIGUSR1);

echo "Done\n";

?>