Skip to content

Instantly share code, notes, and snippets.

@mattes
Created October 31, 2012 13:54
Show Gist options
  • Save mattes/3987146 to your computer and use it in GitHub Desktop.
Save mattes/3987146 to your computer and use it in GitHub Desktop.
watch directory for changes and print "update" on change
#include <sys/event.h>
#include <sys/time.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <iostream>
int main (int argc, const char *argv[])
{
// argv[1]
int f, kq, nev;
struct kevent change;
struct kevent event;
kq = kqueue();
// if (kq == -1)
// perror("kqueue");
f = open("/Users/max/directory", O_RDONLY); // it wont watch subdirs
// if (f == -1)
// perror("open");
EV_SET(&change, f, EVFILT_VNODE,
EV_ADD | EV_ENABLE | EV_ONESHOT,
NOTE_DELETE | NOTE_EXTEND | NOTE_WRITE | NOTE_ATTRIB,
0, 0);
for (;;) {
nev = kevent(kq, &change, 1, &event, 1, NULL);
if (nev == -1) {
// perror("kevent");
}
else if (nev > 0) {
if (event.fflags & NOTE_DELETE) {
std::cout << "update\n"; // File deleted
break;
}
if (event.fflags & NOTE_EXTEND ||
event.fflags & NOTE_WRITE)
std::cout << "update\n"; // File modified
if (event.fflags & NOTE_ATTRIB)
std::cout << "update\n"; // File attributes modified
}
}
close(kq);
close(f);
return EXIT_SUCCESS;
}
@mattes
Copy link
Author

mattes commented Oct 31, 2012

there is an issue with stdout and stderr.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment