我有以下代码,它运行一个永远运行的进程(直到终止)并显示结果(使用下面的tail-F作为示例):
<?php
$cmd = "tail -F /var/log/whatever.log";
set_time_limit(0);
$handle = popen($cmd, "r");
if (ob_get_level() == 0)
ob_start();
while(!feof($handle)) {
$buffer = fgets($handle);
echo $buffer . "<br />";
ob_flush();
flush();
sleep(1);
}
pclose($handle);
ob_end_flush();
?>
这种方法有效,我的进程运行,但当我停止加载页面、关闭选项卡等时,它会继续运行。
当我不显示页面时,有没有什么机制可以让我停止这个过程?我肯定有,但不清楚。
...
header("Content-type:text/html");// start the content serving
echo("'n"); // connection with the browser
while(!feof($handle)) {
$buffer = fgets($handle);
echo $buffer . "<br />";
ob_flush();
flush();
sleep(1);
if (connection_status()!=0){ // check the connection
die; // or whatever you want to stop the work
}
}