如果 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 函数或类可以执行类似的操作?
Edit:Ben Lee 的回答pcnt_fork
这将是完美的解决方案,只是它不适用于 Windows。有没有其他方法可以使用适用于 Windows 和 Linux 的 PHP 来完成此任务,但不需要外部库?
Edit 2:XzKto 的解决方案在某些情况下有效,但不一致,而且无论我尝试什么,我似乎都无法捕获异常。该用例正在检测单元测试的超时。如果测试超时,我想终止它,然后继续下一个测试。
您可以通过分叉进程,然后使用父进程来监视子进程来实现此目的。pcntl_fork http://php.net/manual/en/function.pcntl-fork.php是一种分叉进程的方法,因此内存中有两个几乎相同的程序并行运行。唯一的区别是,在一个进程中,父进程,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 https://www.php.net/manual/en/function.posix-kill.php。所以父进程应该等待 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
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)