php - "real"执行时间限制

标签 php execution-time

使用set_time_limit()ma​​x_execution_time,并不“真正”限制(Windows 上除外)执行时间,因为如 PHP 手册中所述:

Note:

The set_time_limit() function and the configuration directive 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.

解决方案是 proposed in PHP comments像我正在寻找的那样有一个“真正的”执行时间限制,但我发现它不清楚/令人困惑。

最佳答案

我可能是错的,但据我了解,您要求解释“PHP注释”解决方案代码。

诀窍是使用pcntl_fork函数生成一个子进程,该函数将在超时后终止原始(父)进程。函数pcntl_fork返回父进程执行线程内新创建的子进程的进程ID,并返回子进程执行线程内的零。这意味着父进程将执行if语句下的代码,子进程将执行else下的代码。从代码中我们可以看到,父进程将执行无限循环,而子进程将等待 5 秒,然后杀死其父进程。所以基本上你想做这样的事情:

$real_execution_time_limit = 60; // one minute

if (pcntl_fork())
{
    // some long time code which should be
    // terminated after $real_execution_time_limit seconds passed if it's not
    // finished by that time
}
else
{
    sleep($real_execution_time_limit);
    posix_kill(posix_getppid(), SIGKILL); 
}

我希望我已经解释得很好了。如果您对此解决方案仍有疑问,请告诉我。

关于php - "real"执行时间限制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7569573/

相关文章:

c - 错误 - 在 C 中执行的时间

c++ - main() 能否在所有 cout 写入控制台之前返回?

php - 每 24 小时运行一次 php 任务

php - 可以处理缺失字符的 MySQL 查询

php - 响应式表和 mysql

android - MediaCodec解码时间计算

php - 使用 PHP 将 SMS AT 命令发送到 3G 调制解调器

php - 如何在页面上添加按字母顺序分页

c# - 如何在不到 6 小时的执行时间内测试 500 万亿个组合

r - Rscript 和 Littler 之间的区别