![]() |
Tutorial Watching file system events with inotify - Printable Version +- Sinisterly (https://sinister.ly) +-- Forum: Coding (https://sinister.ly/Forum-Coding) +--- Forum: C, C++, & Obj-C (https://sinister.ly/Forum-C-C-Obj-C) +--- Thread: Tutorial Watching file system events with inotify (/Thread-Tutorial-Watching-file-system-events-with-inotify) |
Watching file system events with inotify - Inori - 08-28-2017 If you're trying to write event-driven code that fires on certain file system events (e.g. file access, modification, creation, deletion) for projects like auto-build systems, event logs, or weird shit like this (which I should finish eventually), inotify is the tool for the job. If you're running any derivative of Unix (e.g. Linux or OSX) the inotify library is almost definitely on your system given it's part of glibc, so there's virtually no need to check for it. To start, we need to include some headers and define some constants. Code: // io & file functions Next we need to create our buffer and initialize inotify, checking for errors returned by the function. Code: int main(int argc,char **argv){ After initializing, we can start watching directories using the inotify_add_watch() function. In our case, we'll make a function and call it using the first argument passed to our program (it's argv[1], as argv[0] is the program name). The mask in the third argument represents some of many event flags offered by the library, all of which you can find here. As well, we need to call some cleanup functions at the end of main(), before we return. Code: int add_watch_dir(int fd,char *dirname,uint32_t mask){ Next, we can finally start getting event reports. We need to create an infinite loop to constantly check, two variables to hold the current size of the buffer and the current event index in the given iteration, and a final variable to hold the event itself. After checking errors at the start of the loop, we can go through the available events, check their masks, and take whatever action we see fit from there. I choose to make this a separate function to keep things organized, but you can cram it into main if you'd like (but that doesn't mean you should ![]() Code: // macro for reporting file or directory This serves as a working example (see this gist for the code), but we can go one better by recursing subdirectories (thread coming soon). RE: Watching file system events with inotify - titbang - 09-01-2017 This could come in handy. I was relying on the inotify bin to update my media library when using minidlna for my recently added folder. I might just have to implement this instead. |