php inotify blocking but with timeout

吃可爱长大的小学妹 提交于 2019-12-11 03:06:24

问题


I want to use the pecl extension to php and use the inotify_read() function to detect changes in a file.

As a fail safe, I would like to specify a timeout value to the inotify_read function, just so I don't wind up blocking forever, in case an event is raised and is missed.

Does anyone know how to use the stream_select function to block for a specified number of seconds, but return immediately if an event is raised on the inotify_read.

I know there is way to perform the inotify_read non-blocking, but I don't want to sit there and poll, and I don't want the lag between when the file change happens vs. when I'll be informed by it.

I was able to use pcntl_alarm to interrupt the the system call, but I was hoping for something less intense.


回答1:


Looks like the pecl inotify_init() function returns a php_stream wrapper around the underlying file descriptor. So yes, you should be able to use stream_select() to wait for something to signal the inotify descriptor.

Something like the following should work:

$in = inotify_init();
stream_set_blocking($in, false); // probably a good idea to make it non-blocking
$r = array($in);
$timeout = 10;
$n = stream_select($r, $w = array(), $e = array(), $timeout);
if ($n == 0) {
   // Timed out, so do something else
} else {
   // We know that inotify_read will not block; use it and process
   // the results
}


来源:https://stackoverflow.com/questions/24046702/php-inotify-blocking-but-with-timeout

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!