php - Linux 上 PHP 的真实 max_execution_time

标签 php mysql apache ubuntu timeout

According to the documentation:

max_execution_time only affect the execution time of the script itself. 
Any time spent on activity that happens outside the execution of the script
such as system calls using system(), stream operations, database queries, etc.
is not included when determining the maximum time that the script has been running.
This is not true on Windows where the measured time is real.

这是通过测试证实的:

不会超时

<?php
set_time_limit(5);
$sql = mysqli_connect('localhost','root','root','mysql');
$query = "SELECT SLEEP(10) FROM mysql.user;";
$sql->query($query) or die($query.'<br />'.$sql->error);
echo "You got the page";

会超时

<?php
set_time_limit(5);
while (true) {
  // do nothing
}
echo "You got the page";

我们的问题是我们真的希望 PHP 在给定的时间后超时,不管它在做什么(因为如果我们知道我们未能在可接受的时间量,例如 10 秒)。我们知道我们可以使用诸如 MySQL wait_timeout 之类的设置。对于 SQL 查询,页面超时将取决于执行的查询数。

有些人试图想出 workarounds而且它似乎无法实现。

问:是否有一种简单的方法可以在 Linux 上获得真正的 PHP max_execution_time,或者我们是否可以在其他地方更好地计时,例如 Apache 级别?

最佳答案

这是一个相当棘手的建议,但如果您愿意修改并重新编译 PHP,它肯定会满足您的要求。

https://github.com/php/php-src/blob/master/Zend/zend_execute_API.c 查看 PHP 源代码(文件是 Zend/zend_execute_API.c),在函数 zend_set_timeout 处。这是实现时间限制的功能。以下是它在不同平台上的工作方式:

  • 在 Windows 上,创建一个新线程,在其上启动一个计时器,当它完成时,将一个名为 timed_out 的全局变量设置为 1,PHP 执行核心会在每次执行时检查此变量指令,然后退出(非常简化)

  • 在 Cygwin 上,使用带有 ITIMER_REAL 的计时器,它测量真实时间,包括任何 sleep 、等待等,然后发出一个信号来中断任何处理和停止处理

  • 在其他 unix 系统上,将 itimer 与 ITIMER_PROF 一起使用,它仅测量当前进程(但在用户模式和内核模式下)花费的 CPU 时间。这意味着等待其他进程(如 MySQL)不计入此。

现在您要做的是将 Linux 上的定时器从 ITIMER_PROF 更改为 ITIMER_REAL,这当然需要您手动执行、重新编译、安装等。这两者之间的另一个区别是它们在运行时也使用不同的信号计时器用完了。所以我的建议是更改 ifdef:

#   ifdef __CYGWIN__

进入

#   if 1

以便您将 ITIMER_REAL 和 PHP 等待的信号都设置为 SIGALRM。

无论如何,整个想法都未经测试(我将它用于一些非常具体的系统,其中 ITIMER_PROF 已损坏,但它似乎可以工作),不受支持等。使用它需要您自担风险。它可能与 PHP 本身一起工作,但它可能会破坏 Apache 中的 PHP 中的其他模块,如果它们出于某种原因使用 SIGALRM 信号或其他计时器。

关于php - Linux 上 PHP 的真实 max_execution_time,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10025902/

相关文章:

php - 数据未插入数据库到表中

php - 将 PHP 数组回显为 HTML?

mysql - 在 mysql_query 中触发多个查询

php - 如何使用 mysql -php 根据其category_id 检索 woocommerce 产品详细信息

php - 2checkout 总是返回哈希不匹配

php - HTML 转化为 PHP 变量(PHP 代码之外的 HTML)

mysql查询: match against using wildcard

Apache 反向代理 https 配置导致 503 错误

eclipse - 本地主机上的服务器 Tomcat v8.0 无法启动 : Failed to Start Component in Eclipse for JSP

php - 字体不会显示在 php include 的标题中