我试图在 PHP 中建立一个小恶魔, 分析 Linux 系统中的日志文件 。 (例如, 跟随系统) 。
我设法通过 fopen
打开了文件, 并用 stream_get_line
直接读了它。 当被监视的文件被删除并重新创建( 例如, 当旋转日志时) 时, 我的问题就开始了。 程序不再读了, 即使文件比以前大 。
是否有优雅的解决方案? stream_get_meta_data
无助于解决问题,在命令行使用 tail -f
也存在同样的问题。
EDIT, added sample code I tried to boil down the code to a minimum to illustrate what I am looking for
<?php
$break=FALSE;
$handle = fopen( ./testlog.txt , r );
do {
$line = stream_get_line($handle, 100, "
");
if(!empty($line)) {
// do something
echo $line;
}
while (feof($handle)) {
sleep (5);
$line = stream_get_line($handle, 100, "
");
if(!empty($line)) {
// do something
echo $line;
}
// a commented on php.net indicated it is possible
// with tcp streams to distinguish empty and lost
// does NOT work here --> need somefunction($handle)
if($line !== FALSE && $line = ) $break=TRUE;
}
} while (!$break);
fclose($handle);
?>