开发者

"real" execution time limit

Using set_time_limit() or max_execution_time, does not "really" limits (except on Windows) the execution time, because as stated in PHP manual:

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 act开发者_StackOverflow社区ivity 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.

A solution is proposed in PHP comments to have a "real" execution time limit like what I'm looking for, but I found it unclear/confusing.


I might be wrong, but as far as I understand you ask for explanation of the "PHP comments" solution code.

The trick is to spawn a child process, using pcntl_fork function, which will terminate the original (parent) process after some timeout. Function pcntl_fork returns process id of newly created child process inside a parent process execution thread and zero inside child process execution thread. That means parent process will execute the code under if statement and the child process will execute code under else. And as we can see from the code, the parent process will perform endless loop while child process will wait 5 seconds and then kill his parent. So basically you want to do something like this:

$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); 
}

I hope I've exlained it well. Let me know if you sill have question regarding this solution.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜