Linux has a relatively new (2.6.13, June 2005), easy-to-use interface to watch and monitor file operation: inotify. See the Linux Journal article also.
I plan to use it to see when new devices show up under /dev
:
#includestatic const char *progname = "ino"; static const char *inotify_mask_str(unsigned mask) { switch (mask) { case IN_CREATE: return "create"; case IN_DELETE: return "delete"; default: return "???"; } } int main() { int fd = inotify_init1(0); if (fd < 0) { fprintf(stderr, "%s: init failed\n", progname); exit(EXIT_FAILURE); } int wd = inotify_add_watch(fd, "/dev", IN_CREATE | IN_DELETE); if (wd < 0) { fprintf(stderr, "%s: add watch failed\n", progname); exit(EXIT_FAILURE); } while (true) { uint8_t buf[sizeof(struct inotify_event) + FILENAME_MAX + 1]; ssize_t ret = read(fd, &buf, sizeof(buf)); if (ret < 0) { if (errno == EINTR) continue; fprintf(stderr, "%s: read failed\n", progname); exit(EXIT_FAILURE); } size_t processed = 0; while (processed < ret - sizeof(struct inotify_event)) { struct inotify_event *iev = (struct inotify_event *) &buf[processed]; printf("%4zd:%08x %s %s\n", ret, iev->mask, inotify_mask_str(iev->mask), iev->name); processed += sizeof(struct inotify_event) + iev->len; } } close(wd); close(fd); return EXIT_SUCCESS; }
posted at: 15:31 | path: /programming | permanent link