#include #include #include #include using namespace std; void process_event(const string &name, int event) { string msg; switch (event) { case IN_ACCESS: msg = "was read"; break; case IN_ATTRIB: msg = "metadata changed"; break; case IN_CLOSE_WRITE: msg = "opened for writing was closed"; break; case IN_CLOSE_NOWRITE: msg = "opened for reading was closed"; break; case IN_CREATE: msg = "created in watched directory"; break; case IN_DELETE: msg = "deleted from watched directory"; break; case IN_DELETE_SELF: msg = "was itself deleted"; break; case IN_MODIFY: msg = "was modified"; break; case IN_MOVE_SELF: msg = "was itself moved"; break; case IN_MOVED_FROM: msg = "moved out of watched directory"; break; case IN_MOVED_TO: msg = "moved into watched directory"; break; case IN_OPEN: msg = "was opened"; break; case IN_ISDIR: return; // Ignore this one default: cerr << "Unknown event " << hex << event << '\n'; } cout << name << ' ' << msg << '\n'; } void get_events(int fd, const string &target) { /* Allow for 1024 simultaneous events */ const int BUFF_SIZE = (sizeof(inotify_event)+FILENAME_MAX)*1024; char buff[BUFF_SIZE]; inotify_event *pevent; const ssize_t len = read(fd, buff, BUFF_SIZE); for (ssize_t i=0; ilen) { pevent = reinterpret_cast(&buff[i]); string label = (pevent->len) ? pevent->name : target; int mask = pevent->mask; for (int bit = 1; mask != 0; bit <<= 1) { if (mask & bit) process_event(label, bit); mask &= ~bit; } } } int main (int argc, char *argv[]) { const string target = argc < 2 ? "." : argv[1]; cout << "Watching " << target << '\n'; int fd = inotify_init(); if (fd < 0) { cerr << argv[0] << ": can't inotify_init()\n"; return 1; } if (inotify_add_watch(fd, target.c_str(), IN_ALL_EVENTS) < 0) { cerr << argv[0] << ": can't inotify_add_watch()\n"; return 1; } for (;;) get_events(fd, target); return 0; }