diff options
author | John Ankarström <john@ankarstrom.se> | 2021-07-22 11:26:23 +0200 |
---|---|---|
committer | John Ankarström <john@ankarstrom.se> | 2021-07-22 11:30:09 +0200 |
commit | 46345060aa9414aad838acad2af11176fa094891 (patch) | |
tree | 38d9e86cb16102fd1b04aa34be3d959546c99076 /when.c | |
parent | 94f90dc4f48ee7f6bc1aa3a1116f20b714df89c9 (diff) | |
download | when-46345060aa9414aad838acad2af11176fa094891.tar.gz |
Rename to when
This is to resolve the name conflict with another program called
watch, which is for watching command output.
Diffstat (limited to 'when.c')
-rw-r--r-- | when.c | 75 |
1 files changed, 75 insertions, 0 deletions
@@ -0,0 +1,75 @@ +#include <err.h> +#include <fcntl.h> +#include <stdio.h> +#include <string.h> +#include <sys/event.h> +#include <unistd.h> + +#define FD 27 +#define MAXFILES 100 +#define MAXFD 127 /* FD + MAXFILES */ + +int +main(int argc, char *argv[argc]) +{ + char *filenames[MAXFD]; + int fd, i, kq, n; + struct kevent evs[MAXFILES]; + struct kevent ev[MAXFILES]; + + /* parse arguments */ + if (argc-1 == 0) goto usage; + if (argv[1][0] == '-') { + if (argv[1][1] == 'i') + for (i = 2; i < argc; i++) + printf("%s\n", argv[i]); + else if (argv[1][1] == '-') ; + else goto usage; + argv++; argc--; + } + if (argc-1 == 0) goto usage; + if (argc-1 > MAXFILES) + errx(1, "more than %d files", MAXFILES); + + /* disable buffering even non-interactively */ + setbuf(stdout, NULL); + + /* initialize kqueue */ + if ((kq = kqueue()) == -1) + err(1, "kqueue"); + + /* process each file */ + for (i = 1; i < argc; i++) { + if ((fd = open(argv[i], O_RDONLY)) == -1) + err(1, "%s", argv[i]); + + filenames[fd] = argv[i]; + EV_SET(ev+i-1, fd, EVFILT_VNODE, EV_ADD|EV_CLEAR, + NOTE_WRITE|NOTE_DELETE, 0, 0); + } + + /* register events to watch for */ + if (kevent(kq, ev, argc-1, NULL, 0, NULL) == -1) + err(1, "kevent"); + + for (;;) { + if ((n = kevent(kq, NULL, 0, evs, argc-1, NULL)) == -1) + err(1, "kevent"); + for (i = 0; i < n; i++) { + if (evs[i].fflags & NOTE_WRITE) + printf("%s\n", filenames[evs[i].ident]); + if (evs[i].flags & EV_ERROR) + fprintf(stderr, "event error: %s\n", + strerror(evs[i].data)); + if (evs[i].fflags & NOTE_DELETE) { + fprintf(stderr, "%s deleted\n", + filenames[evs[i].ident]); + close(evs[i].ident); + } + } + } + +usage: + fprintf(stderr, "usage: %s [-i] file\n", argv[0]); + return 1; +} |