Ok, I'm in need of a dir monitor that continually scans a dir for new .txt files added. Opens the .txt file, reads/parses the content and writes data to a mysql table. I'm looking into inotify which seems like it is robust and can accomplish this task, but I don't quiet understand how the command sequence would look to accomplish what I mentioned above.
Here is a potential example (tell me if I'm thinking through this properly):
$fd = inotify_init();
$watch_descriptor = inotify_add_watch($fd, '/some/system/dir/', IN_CREATE);
// Loop forever (never break out of loop since I want to ALWAYS monitor this dir)
while (true) {
$events = inotify_read($fd);
//THIS IS WHERE I DON'T KNOW HOW TO OPEN THE NEWLY CREATED FILE
//PLEASE HELP HERE WITH HOW TO SUCCESSFULLY CREATE THE EVENT ACTIONS
/*
1) OPEN FILE
2) READ/PARSE CONTENTS
3) CREATE MYSQL INSERT STATEMENT
4) DELETE FILE
*/
}
One question this brings up is: Will continuing this loop forever consume a ridiculous amount of processor capacity? and: If so, is this truly the method I should use to accomplish my goal?
Any help understanding inotify and the sequence required to accomplish my goal would be very helpful.
Thank you in advance.
Alright, so this is what I've got so far (thoughts?):
$dir = '/some/system/dir/';
//create mysql database connection here
$fd = inotify_init();
$watch_descriptor = inotify_add_watch($fd, $dir, IN_CREATE);
while (true) {
$events = inotify_read($fd);
$filepath = $dir . $events['name'];
$contents = file_get_contents( $filepath );
//parse contents and insert records into mysql table (thats the easy part)
unlink( $filepath );
}
//close mysql database connection here
inotify_rm_watch($fd, $watch_descriptor);
fclose($fd);
It has also been brought to my attention that inotify will engage in process blocking when an event is not being triggered to free system memory and processor capacity (which addresses my concern about the infinite while loop).
Use inotify_read($fd)
to get information from the generated event.
There's a reasonable example over at php.net: http://www.php.net/manual/en/function.inotify-init.php
As for the while loop, inotify_read() will block until there is an event, so it's not as if it's going to be doing a constant spin.