2015-12-04 41 views
0

我可以停止停止PHP的exec()使用的set_time_limit

exec("Ping www.google.com"); 

使用 “的ini_set( '的max_execution_time',5)” 或 “参数或者set_time_limit(5)” 但不

exec("java myclass"); //infinite Loop class 

为什么呢?以及如何停止exec()?

让我们说,我想运行的Java类包含:

for(int A = 0; A == 0;) 
{ 
    System.out.println(A + " "); 
} 

如何使用PHP阻止他们?

注:我不能编辑java文件(我也想运行不同的类,它不是无限运行)

+0

我会尝试做的是启动过程中的背景让他的PID(的东西,如“&回声$!”在命令结束),然后终止该进程(与PID)此刻我需要它。 – jolmos

+0

Unix还是Windows? –

+0

这是Windows(10) – LedleLee

回答

0

你可以尝试创建一个exec.php文件放到你的代码中

<?php 
ini_set('max_execution_time', 5) 
exec("java myclass"); 
?> 

和您需要执行exec("PATH/exec.php")而不是exec("java myclass");

+0

它只是在记事本上打开exec.php,任何建议? – LedleLee

+0

我不明白你的记事本是什么意思?我的建议是将'<?php exec(“PATH/exec.php”)?>'放在你的php脚本中,而不是'exec(“java myclass”);'调用并添加PATH路径到'exec。 php'不应该打开任何记事本 – Armen

0

由于documentation解释说,这只是不便于携带:

的set_time_limit()函数的功能和配置指令 的max_execution_time只影响脚本本身 的执行时间。任何时间花费在脚本的执行 以外的活动上,例如使用system(),流操作, 数据库查询等进行的系统调用,不包括确定脚本运行时的最长 时间。这是在Windows上不正确 其中测量时间是真实的。

但在实践中,我发现Windows并不一定以这种方式工作。所以,而不是非便携式,我会说这是不可能的。

您将不得不使用更先进的Process Control Extensions,通常类似PCNTL

+0

你能解释一下“exec('ping www.stackoverflow。com)“与exec(”java myclass“),我认为它是一样的,因为它们都运行在CMD中 - 仍然thx为您的信息 – LedleLee

0

您可以使用proc_函数来获得更好的控制。你会发现它在manual。 下面你会发现你可能会觉得有用的代码。它只能在windows下运行,你需要在linux上有一个不同的kill例程。大约5秒钟后,该脚本终止(或者无休止的运行)ping过程。

<?php 
function kill($pid){ 
    return stripos(php_uname('s'), 'win')>-1 ? exec("taskkill /F /T /PID $pid") : exec("kill -9 $pid"); 
} 

$descriptorspec = array(
    0 => array("pipe", "r"), // stdin is a pipe that the child will read from 
    1 => array("pipe", "w"), // stdout is a pipe that the child will write to 
    2 => array("file", "tmp/error-output.txt", "a+") // stderr is a file to write to 
); 

$process = proc_open("Ping www.google.com -t",$descriptorspec,$pipes); 

$terminate_after = 5; // seconds after process is terminated 

usleep($terminate_after*1000000); // wait for 5 seconds 

// terminate the process 
$pstatus = proc_get_status($process); 
$PID = $pstatus['pid']; 

kill($PID); // instead of proc_terminate($resource); 
fclose($pipes[0]); 
fclose($pipes[1]); 
proc_close($process); 

$time = microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"]; 
echo 'Process terminated after: '.$time; 
+0

usleep()使PHP等待5秒的权利吗?但如果其他Java类,我想运行完成只需3秒,这意味着PHP仍需要等待5秒钟? – LedleLee

+0

您可以使用'proc_get_status()'方法来检查您的Java应用程序是否仍在运行或已完成或终止。状态每一秒,你会没事的。 –