gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-10-31 22:53:28 25 4
gpt4 key购买 nike

在我的脚本在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com