php - 检测 PHP 代码块的超时

标签 php timeout

如果 PHP 中的代码块花费太长时间,有没有办法可以中止该代码块?也许是这样的:

//Set the max time to 2 seconds
$time = new TimeOut(2);
$time->startTime();

sleep(3)

$time->endTime();
if ($time->timeExpired()){
    echo 'This function took too long to execute and was aborted.';
} 

它不必与上面完全相同,但是是否有任何本地 PHP 函数或类可以执行类似的操作?

编辑:Ben Lee 使用 pcnt_fork 的回答将是完美的解决方案,只是它不适用于 Windows。有没有其他方法可以使用适用于 Windows 和 Linux 但不需要外部库的 PHP 来实现此目的?

编辑 2:XzKto 的解决方案在某些情况下有效,但不一致,而且无论我尝试什么,我似乎都无法捕获异常。该用例正在检测单元测试的超时。如果测试超时,我想终止它,然后继续下一个测试。

最佳答案

您可以通过 fork 进程,然后使用父进程来监视子进程来实现此目的。 pcntl_fork是一种 fork 进程的方法,因此内存中有两个几乎相同的程序并行运行。唯一的区别是,在一个进程中,父进程 pcntl_fork 返回一个正整数,该整数对应于子进程的进程 ID。在另一个进程中,子进程 pcntl_fork 返回 0。

这是一个例子:

$pid = pcntl_fork();
if ($pid == 0) {
    // this is the child process
} else {
    // this is the parent process, and we know the child process id is in $pid
}

这就是基本结构。下一步是添加流程到期时间。你的东西将在子进程中运行,父进程将只负责监视和计时子进程。但是为了让一个进程(父进程)杀死另一个进程(子进程),需要有一个信号。信号是进程通信的方式,表示“你应该立即结束”的信号是SIGKILL。您可以使用 posix_kill 发送此信号。所以父进程应该等待 2 秒然后杀死子进程,如下所示:

$pid = pcntl_fork();
if ($pid == 0) {
    // this is the child process
    // run your potentially time-consuming method
} else {
    // this is the parent process, and we know the child process id is in $pid
    sleep(2); // wait 2 seconds
    posix_kill($pid, SIGKILL); // then kill the child
}

关于php - 检测 PHP 代码块的超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7493676/

相关文章:

php - ajax 文件上传仅在 SSL 终止负载平衡器时失败

javascript - 循环时使用 on click 添加数据

php - PHP 如何四舍五入到小数点后两位

c# - SqlConnection 超时异常

php - PHP Fun 的 Apache 500 错误

PHP 超时覆盖没有明确的解释

angularjs - Angular promise 超时失败

php - 在字符串(大约 500 个字符)中搜索关键字(来自矩阵)

php - 警告 : mysql_connect(): [2002] No such file or directory (trying to connect via unix:///tmp/mysql. socks )中

MySQL 需要很长时间(数小时)来确定丢失的连接