Skip to content

Instantly share code, notes, and snippets.

@yujiorama
Created November 17, 2009 13:28
Show Gist options
  • Save yujiorama/236898 to your computer and use it in GitHub Desktop.
Save yujiorama/236898 to your computer and use it in GitHub Desktop.
#ifdef __cplusplus
extern "C" {
#endif
#include <sys/types.h>
#include <sys/event.h>
#include <sys/time.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>
#include <time.h>
#include <unistd.h>
#ifdef __cplusplus
}
#endif
int
register_watch_file(char* filename) {
// target
struct kevent kev;
memset(&kev, 0, sizeof(struct kevent));
int fd = open(filename, O_RDONLY, 0);
EV_SET(&kev, fd, EVFILT_VNODE, EV_ADD|EV_ENABLE|EV_CLEAR, NOTE_WRITE, 0, NULL);
// register
int kq = kqueue();
kevent(kq, &kev, 1, NULL, 0, NULL);
return kq;
}
int
main(int argc, char** argv) {
if (argc != 2) {
perror("usage: ./kqueue_test <file>");
printf("argc: %d\n", argc);
return 1;
}
int kq = register_watch_file(argv[1]);
struct kevent kev;
time_t timer;
memset(&kev, 0, sizeof(struct kevent));
for (;;) {
if (kevent(kq, NULL, 0, &kev, 1, NULL) > 0) {
if ((kev.fflags & NOTE_WRITE) == NOTE_WRITE) {
timer = time(NULL);
printf("%swrite! %s\n", asctime(localtime(&timer)), argv[1]);
}
}
}
close(kq);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment