使PHP等待Matlab脚本完成执行 [英] Make PHP wait for Matlab script to finish executing
问题描述
Possible Duplicate:
php exec command (or similar) to not wait for result
exec() waiting for a response in PHP
我有一个调用并运行Matlab脚本的php脚本. Matlab脚本的结果是一个.png图像,然后我想将其加载到php中并发送到网页.我拥有的php代码是:
I have a php script that calls and runs a Matlab script. The result of the Matlab script is a .png image, which I would then like to load in php and send to a webpage. The php code I have is:
$matlabExe = '"C:\\Program Files\\MATLAB\\R2012a\\bin\\matlab.exe"';
$mFile = "'C:\\processSatData.m'";
$combine = '"run(' . $mFile . ');"';
$command = $matlabExe . ' -nodisplay -nosplash -nodesktop -r ' . $combine;
passthru($command);
$im = file_get_contents('C:\\habitat.png');
header('Content-type:image/png');
echo $im;
但是,似乎在发送"passthru"命令后,php并不等待Matlab脚本完成运行.因此,如果在运行php代码之前图像文件不存在,那么我会收到一条错误消息.
However, it appears that after sending the 'passthru' command, php does not wait for the Matlab script to finish running. Thus, if the image file does not exist before running the php code, then I get an error message.
有没有一种方法可以使php代码在尝试加载图像文件之前等待Matlab脚本完成运行?
Is there a way to make it so that the php code waits for the Matlab script to finish running before it attempts to load the image file?
推荐答案
passthru
不是这里的主要问题..但我想,一旦您收到命令的响应,图像不会立即写入,而是由第三个写入处理
passthru
is not the main issue here .. but i guess as soon you have a response from your command the image is not written instantly but by a 3rd process
file_get_contents
在这种情况下也可能会失败,因为..图像可能不会一次写入或在写入过程中可能会导致文件锁定..在任何情况下,您都需要先确保拥有有效的图像输出已发送;
file_get_contents
might also fail in this instance because .. The image might not be written once or in the process of writing which can result to file lock .. in any case you need to be sure you have a valid image before output is sent;
set_time_limit(0);
$timeout = 30; // sec
$output = 'C:\\habitat.png';
$matlabExe = '"C:\\Program Files\\MATLAB\\R2012a\\bin\\matlab.exe"';
$mFile = "'C:\\processSatData.m'";
$combine = '"run(' . $mFile . ');"';
$command = $matlabExe . ' -nodisplay -nosplash -nodesktop -r ' . $combine;
try {
if (! @unlink($output) && is_file($output))
throw new Exception("Unable to remove old file");
passthru($command);
$start = time();
while ( true ) {
// Check if file is readable
if (is_file($output) && is_readable($output)) {
$img = @imagecreatefrompng($output);
// Check if Math Lab is has finished writing to image
if ($img !== false) {
header('Content-type:image/png');
imagepng($img);
break;
}
}
// Check Timeout
if ((time() - $start) > $timeout) {
throw new Exception("Timeout Reached");
break;
}
}
} catch ( Exception $e ) {
echo $e->getMessage();
}
这篇关于使PHP等待Matlab脚本完成执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!