php - 在 CLI 上的脚本中止后执行代码

标签 php command-line-interface

在我的脚本在 PHP 中中止后,我尝试执行一些最终代码。假设我有这个 PHP 脚本:

while(true) {
    echo 'loop';
    sleep(1);
}

如果我使用 $ php script.php 执行脚本,它会一直运行到给定的执行时间。

现在我喜欢在脚本中止后执行一些最终代码。所以如果我

  • 点击 Ctrl+C
  • 执行时间结束

在这些情况下甚至有可能进行一些清理吗?

我用 pcntl_signal 试过了但没有运气。还有 register_shutdown_function但这只有在脚本成功结束时才会被调用。

更新

我发现(thx to rch's link)我可以通过以下方式“捕捉”事件:

pcntl_signal(SIGTERM, $restartMyself); // kill
pcntl_signal(SIGHUP,  $restartMyself); // kill -s HUP or kill -1
pcntl_signal(SIGINT,  $restartMyself); // Ctrl-C

但是如果我扩展我的代码

$cleanUp = function() {
    echo 'clean up';
    exit;
};

pcntl_signal(SIGINT, $cleanUp);

如果我按 Ctrl+C,脚本会继续执行,但不会遵守 $cleanUp 闭包中的代码。

最佳答案

函数pcntl_signal()是脚本被使用 Ctrl-C(和其他信号)中断的情况的答案。您必须注意文档。它说:

You must use the declare() statement to specify the locations in your program where callbacks are allowed to occur for the signal handler to function properly.

除其他事项外,declare() 语句安装了一个回调函数,该函数通过调用函数 pcntl_signal_dispatch() 来处理自上次调用以来接收到的信号的调度。依次调用您安装的信号处理程序。

或者,您可以调用函数 pcntl_signal_dispatch()当你认为它适合你的代码流时,你自己(并且根本不要使用 declare(ticks=1))。

这是一个使用declare(ticks=1)的示例程序:

declare(ticks=1);

// Install the signal handlers
pcntl_signal(SIGHUP,  'handleSigHup');
pcntl_signal(SIGINT,  'handleSigInt');
pcntl_signal(SIGTERM, 'handleSigTerm');


while(true) {
    echo 'loop';
    sleep(1);
}

// Reset the signal handlers
pcntl_signal(SIGHUP,  SIG_DFL);
pcntl_signal(SIGINT,  SIG_DFL);
pcntl_signal(SIGTERM, SIG_DFL);



/**
 * SIGHUP: the controlling pseudo or virtual terminal has been closed
 */
function handleSigHup()
{
    echo("Caught SIGHUP, terminating.\n");
    exit(1);
}

/**
 * SIGINT: the user wishes to interrupt the process; this is typically initiated by pressing Control-C
 *
 * It should be noted that SIGINT is nearly identical to SIGTERM.
 */
function handleSigInt()
{
    echo("Caught SIGINT, terminating.\n");
    exit(1);
}

/**
 * SIGTERM: request process termination
 *
 * The SIGTERM signal is a generic signal used to cause program termination.
 * It is the normal way to politely ask a program to terminate.
 * The shell command kill generates SIGTERM by default.
 */
function handleSigTerm()
{
    echo("Caught SIGTERM, terminating.\n");
    exit(1);
}

关于php - 在 CLI 上的脚本中止后执行代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30932746/

相关文章:

go - 您可以为 Cobra 中的标志指定可选参数吗?

php - PHP 代码中的 JavaScript 脚本标记

php - 如何使用 PHP 验证我的 'third party server' 上的 GKLocalPlayer?

php - 在 php 中扩展静态方法

java - 如何使用 JAVA 在 file.txt 中写入函数的输出

php - 服务器上不同版本的 PHP 与 CLI

javascript - 添加操作 woocommerce_add_to_cart 破坏网站原始添加到购物车功能

php - 如何互连 Node.js 应用程序服务器和 LAMP 堆栈?

command-line-interface - 如何使用 `argparse` 为 nim 提供可变数量的参数

linux - 使用 ImageMagick 从右到左的文本