1 /* SPDX-License-Identifier: CC0-1.0 */
2 
3 #include <stdio.h>
4 #include <string.h>
5 #include <sys/inotify.h>
6 
7 #include <systemd/sd-event.h>
8 
9 #define _cleanup_(f) __attribute__((cleanup(f)))
10 
inotify_handler(sd_event_source * source,const struct inotify_event * event,void * userdata)11 static int inotify_handler(sd_event_source *source,
12                            const struct inotify_event *event,
13                            void *userdata) {
14 
15   const char *desc = NULL;
16 
17   sd_event_source_get_description(source, &desc);
18 
19   if (event->mask & IN_Q_OVERFLOW)
20     printf("inotify-handler <%s>: overflow\n", desc);
21   else if (event->mask & IN_CREATE)
22     printf("inotify-handler <%s>: create on %s\n", desc, event->name);
23   else if (event->mask & IN_DELETE)
24     printf("inotify-handler <%s>: delete on %s\n", desc, event->name);
25   else if (event->mask & IN_MOVED_TO)
26     printf("inotify-handler <%s>: moved-to on %s\n", desc, event->name);
27 
28   /* Terminate the program if an "exit" file appears */
29   if ((event->mask & (IN_CREATE|IN_MOVED_TO)) &&
30       strcmp(event->name, "exit") == 0)
31     sd_event_exit(sd_event_source_get_event(source), 0);
32 
33   return 1;
34 }
35 
main(int argc,char ** argv)36 int main(int argc, char **argv) {
37   _cleanup_(sd_event_unrefp) sd_event *event = NULL;
38   _cleanup_(sd_event_source_unrefp) sd_event_source *source1 = NULL, *source2 = NULL;
39 
40   const char *path1 = argc > 1 ? argv[1] : "/tmp";
41   const char *path2 = argc > 2 ? argv[2] : NULL;
42 
43   /* Note: failure handling is omitted for brevity */
44 
45   sd_event_default(&event);
46 
47   sd_event_add_inotify(event, &source1, path1,
48                        IN_CREATE | IN_DELETE | IN_MODIFY | IN_MOVED_TO,
49                        inotify_handler, NULL);
50   if (path2)
51     sd_event_add_inotify(event, &source2, path2,
52                          IN_CREATE | IN_DELETE | IN_MODIFY | IN_MOVED_TO,
53                          inotify_handler, NULL);
54 
55   sd_event_loop(event);
56 
57   return 0;
58 }
59