Skip to content

Instantly share code, notes, and snippets.

@gauteh
Created July 7, 2009 11:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save gauteh/142027 to your computer and use it in GitHub Desktop.
Save gauteh/142027 to your computer and use it in GitHub Desktop.
Detects change of ~/.plan
/*
* Copyright (c) 2009 Gaute Hope <eg@gaute.vetsj.com>
* Distributed under the terms of the GNU General Public Licence v2
*
* Waits for change of ~/.plan
*
*/
# include <iostream>
# include <sys/inotify.h>
# include <cstdlib>
# include <cstring>
using namespace std;
const char * get_event_name (uint32_t);
int main () {
int ifd = inotify_init ();
char *home = getenv ("HOME");
int dir = inotify_add_watch (ifd, home, IN_CLOSE_WRITE | IN_DELETE | IN_MOVED_TO);
if (dir == -1) {
close (ifd);
exit (1);
}
const int event_size = sizeof (inotify_event);
/* buffer of max 1024 events.
*
* the string inotify_event->name, if present,
* increases the size of the event structure.
*/
const int buf_len = 1024 * (event_size);
while (1) {
char buf[buf_len];
/* read() reads in events as long as there
* is space in buf[], then continues.
*
* but it will also block when there are no events pending
* and buf[] is empty, otherwise continue.
*/
int len = read (ifd, buf, buf_len);
if (len < 1) {
close (ifd);
exit (1);
}
int i = 0;
while (i < len) {
inotify_event *e = reinterpret_cast<inotify_event *> (&buf[i]);
if (e->len && (strcmp (e->name, ".plan") == 0))
cout << get_event_name (e->mask) << ":: CHANGE OF PLAN!" << endl;
i += event_size + e->len;
}
}
close (ifd);
exit (0);
}
const char * get_event_name (uint32_t mask) {
if (mask & IN_ACCESS) return "IN_ACCESS";
if (mask & IN_ATTRIB) return "IN_ATTRIB";
if (mask & IN_CLOSE_WRITE) return "IN_CLOSE_WRITE";
if (mask & IN_CLOSE_NOWRITE) return "IN_CLOSE_NOWRITE";
if (mask & IN_CREATE) return "IN_CREATE";
if (mask & IN_DELETE) return "IN_DELETE";
if (mask & IN_DELETE_SELF) return "IN_DELETE_SELF";
if (mask & IN_MODIFY) return "IN_MODIFY";
if (mask & IN_MOVE_SELF) return "IN_MOVE_SELF";
if (mask & IN_MOVED_FROM) return "IN_MOVED_FROM";
if (mask & IN_MOVED_TO) return "IN_MOVED_TO";
if (mask & IN_OPEN) return "IN_OPEN";
if (mask & IN_IGNORED) return "IN_IGNORED";
if (mask & IN_ISDIR) return "IN_ISDIR";
if (mask & IN_Q_OVERFLOW) return "IN_Q_OVERFLOW";
if (mask & IN_UNMOUNT) return "IN_UNMOUNT";
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment