我正在读linux中的一个文件,这是一个日志文件,它会不断更新文件是否发生了变化,并将其输出到网页。我使用php inotify来做,但我的问题是它被阻塞了。
我怎样才能让php inotify非阻塞,这样我就可以在它监视文本文件的同时做其他的事情了?
<?php
$fd = inotify_init();
$watch_descriptor = inotify_add_watch($fd, '/tmp/temp.txt', IN_MODIFY);
touch('/tmp/temp.txt');
$events = inotify_read($fd);
$contents = file_get_contents('/tmp/temp.txt');
echo $contents;
inotify_rm_watch($fd, $watch_descriptor);
fclose($fd)
?>或者我可以在java?..Thanks中做到这一点。
发布于 2012-10-29 23:47:44
是的你可以。你看过手册了吗?它提供了非阻塞事件回调示例?如果此答案不足以回答您的问题,请添加更多信息。
http://php.net/manual/en/function.inotify-init.php
// Open an inotify instance
$fd = inotify_init();
// - Using stream_set_blocking() on $fd
stream_set_blocking($fd, 0);
// Watch __FILE__ for metadata changes (e.g. mtime)
$watch_descriptor = inotify_add_watch($fd, __FILE__, IN_ATTRIB);
// generate an event
touch(__FILE__);
// this is a loop
while(true){
$events = inotify_read($fd); // Does no block, and return false if no events are pending
// do other stuff here, break when you want...
}
// Stop watching __FILE__ for metadata changes
inotify_rm_watch($fd, $watch_descriptor);
// Close the inotify instance
// This may have closed all watches if this was not already done
fclose($fd);发布于 2012-12-07 19:02:02
就像雷克说的。你可以选择阻塞或者非阻塞。如果它是非阻塞的,你必须轮询。我认为你想要的是以多线程的方式阻塞。一个线程在阻塞或非阻塞的频繁轮询模式下工作,而另一个线程做其他事情。
发布于 2013-07-18 11:48:44
我建议使用node.js.来做这件事会容易得多。
你只需要下面的代码:(filename:watch.js)
var fs = require('fs');
var file = '/tmp/temp.txt/';
fs.watchFile(file, function (curr, prev) {
console.log('the current mtime is: ' + curr.mtime);
console.log('the previous mtime was: ' + prev.mtime);
});然后,您可以运行它:
node watch.js它将持续运行。
node.js使用javascript编写server-side程序,它具有non-blocking I/O模型。它可以帮助你轻松地完成这类事情。
下面是一些相关的文档fs.watchFile
https://stackoverflow.com/questions/13123409
复制相似问题