PHP Inotify非阻塞方式

dem*_*0de 5 php linux

我正在读取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)

?>
Run Code Online (Sandbox Code Playgroud)

或者我可以在java中这样做吗?..谢谢.

Lay*_*yke 7

是的你可以。你看说明书了吗?它提供了非阻塞事件回调的例子吗?如果此答案不能充分回答您,请添加更多信息。

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);
Run Code Online (Sandbox Code Playgroud)

  • 实际上这是有效的,但 Layke 也包含了阻塞读取调用。我已经更正了代码。 (3认同)