summaryrefslogtreecommitdiff
path: root/inotify.c
diff options
context:
space:
mode:
authorPeter Wu <lekensteyn@gmail.com>2012-09-26 15:04:18 +0200
committerPeter Wu <lekensteyn@gmail.com>2012-09-26 15:04:18 +0200
commit2497c1392b81e093f4de2541a98746aebd449a7f (patch)
treedb87e59d4c70c677ddb1899d9161b004f6e454ac /inotify.c
downloadc-files-2497c1392b81e093f4de2541a98746aebd449a7f.tar.gz
Initial commit
Diffstat (limited to 'inotify.c')
-rw-r--r--inotify.c92
1 files changed, 92 insertions, 0 deletions
diff --git a/inotify.c b/inotify.c
new file mode 100644
index 0000000..d363c77
--- /dev/null
+++ b/inotify.c
@@ -0,0 +1,92 @@
+#include <stdio.h>
+#include <sys/inotify.h>
+#include <unistd.h>
+#include <malloc.h>
+
+#include <error.h>
+#include <errno.h>
+#define fail(msg) error(1, errno, msg)
+
+#ifndef PATH_MAX
+# define PATH_MAX 4096
+#endif
+
+struct ev {
+ int val;
+ char *name;
+};
+
+#define STRVAL(val) #val
+#define IN(name) {IN_##name, STRVAL(name)}
+
+struct ev events[] = {
+ IN(CLOSE_WRITE),
+ IN(CLOSE_NOWRITE),
+ IN(OPEN),
+ {0, NULL}
+};
+
+int main(int argc, char **argv) {
+ int i, ifd, wfd, mask;
+ int wfds[argc - 1];
+ if (argc < 2) {
+ fprintf(stderr, "Usage: %s file_to_watch ...\n", argv[0]);
+ return 1;
+ }
+ for (i=1; i<argc; i++) {
+ printf("file = %s\n", argv[i]);
+ }
+
+ ifd = inotify_init();
+ if (ifd == -1) fail("inotify_init");
+ printf("ifd = %i\n", ifd);
+
+ mask = 0;
+
+ struct ev *event = events;
+ while (event->name != NULL) {
+ mask |= event->val;
+ printf("event IN_%-16s = %8x\n", event->name, event->val);
+ ++event;
+ }
+ for (i=1; i<argc; i++) {
+ wfd = inotify_add_watch(ifd, argv[i], mask);
+ if (wfd == -1) fail("inotify_add_watch");
+ printf("wfd = %i\n", wfd);
+ wfds[i - 1] = wfd;
+ }
+
+ int iev_size = sizeof(struct inotify_event) + PATH_MAX + 1;
+ struct inotify_event *iev = malloc(iev_size);
+ if (!iev) fail("malloc");
+
+ putchar('\n');
+
+ int j = 100;
+ while (--j) {
+ char *file;
+ if (read(ifd, iev, iev_size) == -1) {
+ perror("read");
+ break;
+ }
+ for (i=0; i<argc-1; i++) {
+ if (wfds[i] == iev->wd) {
+ file = argv[i + 1];
+ break;
+ }
+ }
+ printf("wd = %i, mask = %x, name = %s\tfile = %s\n",
+ iev->wd, iev->mask, iev->name,
+ file);
+ }
+
+ free(iev);
+
+ for (i=0; i<argc-1; i++) {
+ wfd = wfds[i];
+ if (inotify_rm_watch(ifd, wfd) == -1) fail("inotify_rm_watch");
+ }
+
+ close(ifd);
+ return 0;
+}