【问题标题】:Can a PHP CLI script detect / fire a callback on script halt?PHP CLI 脚本可以在脚本停止时检测/触发回调吗?
【发布时间】:2014-07-18 15:32:12
【问题描述】:

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

【问题讨论】:

    标签: php command-line-interface


    【解决方案1】:

    我相信pcntl_signal 将允许您处理常规(非 kill -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";
    
    ?>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-11-28
      • 1970-01-01
      • 2015-07-24
      • 2011-12-12
      • 2011-06-29
      • 1970-01-01
      • 2019-05-13
      • 2021-11-01
      相关资源
      最近更新 更多