ATuin

inotify silly example

Jun 20th, 2014
240
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.19 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <linux/inotify.h>
  4. #include <errno.h>
  5. #include <sys/types.h>
  6.  
  7. #define NEVENTS 1
  8. #define NAMEMAX 200
  9. #define EVENT_BUF_LEN (sizeof(struct inotify_event) + NAMEMAX + 1)
  10. #define EVENTS_BUF_LEN  (EVENT_BUF_LEN * NEVENTS)
  11.  
  12. int main (int argc, char** argv) {
  13.     int notify_fd, watch_fd, bytes = 0;
  14.     int events_n = 1;
  15.     struct inotify_event *buff;
  16.  
  17.     notify_fd = inotify_init();
  18.     if (notify_fd < 0) {
  19.     perror("inotify_init() :: ");
  20.     return 1;
  21.     }
  22.  
  23.     watch_fd = inotify_add_watch(notify_fd, "/dev", IN_CREATE | IN_DELETE);
  24.     if (watch_fd < 0) {
  25.     perror("watch_fd() :: ");
  26.     close(notify_fd);
  27.     return 2;
  28.     }
  29.  
  30.     for (;;) {
  31.     buff = malloc(EVENT_BUF_LEN);
  32.     if (!buff) {
  33.         printf("Memory error!");
  34.         close(notify_fd);
  35.         return 3;
  36.     }
  37.     bytes = read(notify_fd, buff, EVENTS_BUF_LEN);
  38.     if (bytes < EVENT_BUF_LEN - NAMEMAX + 1) {
  39.         printf("No enought data");
  40.         free(buff);
  41.         close(notify_fd);
  42.         return 4;
  43.     }
  44.     if (!buff->len) {
  45.         printf("Unexpected error, len of event name undefined");
  46.         free(buff);
  47.         continue;
  48.  
  49.     }
  50.     printf("Device: %s\n", buff->name);
  51.     free(buff);
  52.     }
  53.  
  54.     return 0;
  55. }
Advertisement
Add Comment
Please, Sign In to add comment