2

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 Answer 1

2

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
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for explaining how to use the file descriptor - you should add your code to the php man page!
Its almost 2023, so this is almost 9 years old... None the less, excellent answer!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.