Skip to content

Instantly share code, notes, and snippets.

@laclefyoshi
Created May 7, 2011 06:02
Show Gist options
  • Save laclefyoshi/960248 to your computer and use it in GitHub Desktop.
Save laclefyoshi/960248 to your computer and use it in GitHub Desktop.
using kqueue for monitoring a file
/**
Copyright: (c) SAEKI Yoshiyasu
License : MIT-style license
<http://www.opensource.org/licenses/mit-license.php>
last updated: 2011/05/07
**/
#include<stdio.h>
#include<stdlib.h>
#include <sys/event.h>
int main(int argc, char *argv[]) {
FILE *fp = fopen("foo", "r");
struct kevent kev, kev_r;
int kq = kqueue();
if(kq == -1) {
printf("kqueue error\n");
exit(0);
}
EV_SET(&kev, (*fp)._file, EVFILT_VNODE,
EV_ADD | EV_ENABLE | EV_CLEAR,
NOTE_DELETE | NOTE_WRITE, 0, NULL);
if(kevent(kq, &kev, 1, NULL, 0, NULL) == -1) {
printf("kevent error\n");
exit(0);
}
while(1) {
if(kevent(kq, NULL, 0, &kev_r, 1, NULL) == -1) {
printf("kevent_r error\n");
exit(0);
}
if(kev_r.fflags & NOTE_WRITE) {
printf("file was updated!\n");
} else if(kev_r.fflags & NOTE_DELETE) {
printf("file was deleted!\n");
}
}
fclose(fp);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment