#include #include // Use this if syscalls not defined #ifndef __NR_inotify_init #include #endif // __NR_inotify_init #include #include #include #include using namespace std; typedef map StrIntMap; typedef pair StrIntPair; typedef map IntStrMap; typedef pair IntStrPair; StrIntMap pathsToWds; IntStrMap wdsToPaths; int fd; int AddWatch(const string &path) { int wd = inotify_add_watch( fd, (char*)(path.c_str()), IN_CREATE | IN_DELETE | IN_MODIFY ); pathsToWds.insert(StrIntPair(path, wd)); wdsToPaths.insert(IntStrPair(wd, path)); printf("Adds %s as wd %d. Has %d watches\n", path.c_str(), wd, pathsToWds.size()); return wd; } void RemoveWatch(const string &path) { int wd = pathsToWds[path]; pathsToWds.erase(path); wdsToPaths.erase(wd); printf("Removes %s as wd %d. Has %d watches\n", path.c_str(), wd, pathsToWds.size()); if( inotify_rm_watch(fd, wd) != -1) { throw string("No no no..."); } } void RemoveWatch(int wd) { RemoveWatch(wdsToPaths[wd]); } int main( ) { try { int EVENT_SIZE = sizeof (struct inotify_event) ; int EVENT_BUF_LEN = ( 1024 * ( EVENT_SIZE + 16 ) ); int length, i = 0; char buffer[EVENT_BUF_LEN]; /*creating the INOTIFY instance*/ fd = inotify_init(); /*checking for error*/ if ( fd < 0 ) { // perror( "inotify_init" ); } /*adding the “/tmp” directory into watch list. Here, the suggestion is to validate the existence of the directory before adding into monitoring list.*/ string bd = "/tmp"; AddWatch(bd); while(1) { length = 0; i = 0; length = read( fd, buffer, EVENT_BUF_LEN ); /*checking for error*/ if ( length < 0 ) { perror( "read" ); } /*actually read return the list of change events happens. Here, read the change event one by one and process it accordingly.*/ while ( i < length ) { struct inotify_event *event = ( struct inotify_event * ) &buffer[ i ]; if ( event->len ) { string parentdir; parentdir = wdsToPaths[event->wd]; if ( event->mask & IN_CREATE ) { if ( event->mask & IN_ISDIR ) { printf( "New directory %s created in %s.\n", event->name, parentdir.c_str()); AddWatch(parentdir+"/"+event->name); } else { printf( "New file %s created in %s.\n", event->name, parentdir.c_str()); } } else if ( event->mask & IN_DELETE ) { if ( event->mask & IN_ISDIR ) { printf( "Directory %s deleted in %s.\n", event->name, parentdir.c_str() ); RemoveWatch(parentdir+"/"+event->name); } else { printf( "File %s deleted in %s.\n", event->name, parentdir.c_str()); } } else if ( event->mask & IN_MODIFY) { if ( event->mask & IN_ISDIR ) { printf( "Directory %s modified in %s.\n", event->name, parentdir.c_str()); } else { printf( "File %s modified in %s.\n", event->name, parentdir.c_str()); } } } i += EVENT_SIZE + event->len; } } /*removing the “/tmp” directory from the watch list.*/ /*closing the INOTIFY instance*/ close( fd ); } catch(string s) { printf("Caught: %s\n", s.c_str()); } }