首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >PHP Inotify非阻塞方式

PHP Inotify非阻塞方式
EN

Stack Overflow用户
提问于 2012-10-29 22:17:14
回答 5查看 3.5K关注 0票数 6

我正在读linux中的一个文件,这是一个日志文件,它会不断更新文件是否发生了变化,并将其输出到网页。我使用php inotify来做,但我的问题是它被阻塞了。

我怎样才能让php inotify非阻塞,这样我就可以在它监视文本文件的同时做其他的事情了?

代码语言:javascript
复制
<?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中做到这一点。

EN

回答 5

Stack Overflow用户

发布于 2012-10-29 23:47:44

是的你可以。你看过手册了吗?它提供了非阻塞事件回调示例?如果此答案不足以回答您的问题,请添加更多信息。

http://php.net/manual/en/function.inotify-init.php

代码语言:javascript
复制
// 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);
票数 7
EN

Stack Overflow用户

发布于 2012-12-07 19:02:02

就像雷克说的。你可以选择阻塞或者非阻塞。如果它是非阻塞的,你必须轮询。我认为你想要的是以多线程的方式阻塞。一个线程在阻塞或非阻塞的频繁轮询模式下工作,而另一个线程做其他事情。

票数 2
EN

Stack Overflow用户

发布于 2013-07-18 11:48:44

我建议使用node.js.来做这件事会容易得多。

你只需要下面的代码:(filename:watch.js)

代码语言:javascript
复制
    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);
    });

然后,您可以运行它:

代码语言:javascript
复制
    node watch.js

它将持续运行。

node.js使用javascript编写server-side程序,它具有non-blocking I/O模型。它可以帮助你轻松地完成这类事情。

下面是一些相关的文档fs.watchFile

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13123409

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档