我有一个远程添加的文件(file.txt)。从SSH,我可以调用tail -f file.txt来显示文件的更新内容。我希望能够对此文件执行阻塞调用,该调用将返回最后一个附加行。池循环根本不是一个选项。以下是我想要的:

$cmd = "tail -f file.txt";
$str = exec($cmd);

这段代码的问题是tail永远不会返回。tail是否有一种包装函数,一旦它返回了内容,就会杀死它?有没有更好的方法以低开销的方式来实现这一点?

最佳答案

我找到的唯一解决方案是有点脏:

<?php
$descriptorspec = array(
   0 => array("pipe", "r"),  // stdin
   1 => array("pipe", "w"),  // stdout
   2 => array("pipe", "w")   // stderr
);

$process = proc_open('tail -f -n 0 /tmp/file.txt',$descriptorspec,$pipes);
fclose($pipes[0]);
stream_set_blocking($pipes[1],1);
$read = fgets($pipes[1]);
fclose($pipes[1]);
fclose($pipes[2]);
//if I try to call proc_close($process); here, it fails / hangs untill a second line is
//passed to the file. Hence an inelegant kill in the next 2 line:
$status = proc_get_status($process);
exec('kill '.$status['pid']);
proc_close($process);
echo $read;

关于php - PHP-阻止文件读取,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3950679/

10-11 13:26