wait_inotify.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * Wait until an inotify event on the given cgroup file.
  4. */
  5. #include <linux/limits.h>
  6. #include <sys/inotify.h>
  7. #include <sys/mman.h>
  8. #include <sys/ptrace.h>
  9. #include <sys/stat.h>
  10. #include <sys/types.h>
  11. #include <errno.h>
  12. #include <fcntl.h>
  13. #include <poll.h>
  14. #include <stdio.h>
  15. #include <stdlib.h>
  16. #include <string.h>
  17. #include <unistd.h>
  18. static const char usage[] = "Usage: %s [-v] <cgroup_file>\n";
  19. static char *file;
  20. static int verbose;
  21. static inline void fail_message(char *msg)
  22. {
  23. fprintf(stderr, msg, file);
  24. exit(1);
  25. }
  26. int main(int argc, char *argv[])
  27. {
  28. char *cmd = argv[0];
  29. int c, fd;
  30. struct pollfd fds = { .events = POLLIN, };
  31. while ((c = getopt(argc, argv, "v")) != -1) {
  32. switch (c) {
  33. case 'v':
  34. verbose++;
  35. break;
  36. }
  37. argv++, argc--;
  38. }
  39. if (argc != 2) {
  40. fprintf(stderr, usage, cmd);
  41. return -1;
  42. }
  43. file = argv[1];
  44. fd = open(file, O_RDONLY);
  45. if (fd < 0)
  46. fail_message("Cgroup file %s not found!\n");
  47. close(fd);
  48. fd = inotify_init();
  49. if (fd < 0)
  50. fail_message("inotify_init() fails on %s!\n");
  51. if (inotify_add_watch(fd, file, IN_MODIFY) < 0)
  52. fail_message("inotify_add_watch() fails on %s!\n");
  53. fds.fd = fd;
  54. /*
  55. * poll waiting loop
  56. */
  57. for (;;) {
  58. int ret = poll(&fds, 1, 10000);
  59. if (ret < 0) {
  60. if (errno == EINTR)
  61. continue;
  62. perror("poll");
  63. exit(1);
  64. }
  65. if ((ret > 0) && (fds.revents & POLLIN))
  66. break;
  67. }
  68. if (verbose) {
  69. struct inotify_event events[10];
  70. long len;
  71. usleep(1000);
  72. len = read(fd, events, sizeof(events));
  73. printf("Number of events read = %ld\n",
  74. len/sizeof(struct inotify_event));
  75. }
  76. close(fd);
  77. return 0;
  78. }