poll.c 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * Simple poll on a file.
  4. *
  5. * Copyright (c) 2024 Google LLC.
  6. */
  7. #include <errno.h>
  8. #include <fcntl.h>
  9. #include <poll.h>
  10. #include <stdio.h>
  11. #include <stdlib.h>
  12. #include <string.h>
  13. #include <unistd.h>
  14. #define BUFSIZE 4096
  15. /*
  16. * Usage:
  17. * poll [-I|-P] [-t timeout] FILE
  18. */
  19. int main(int argc, char *argv[])
  20. {
  21. struct pollfd pfd = {.events = POLLIN};
  22. char buf[BUFSIZE];
  23. int timeout = -1;
  24. int ret, opt;
  25. while ((opt = getopt(argc, argv, "IPt:")) != -1) {
  26. switch (opt) {
  27. case 'I':
  28. pfd.events = POLLIN;
  29. break;
  30. case 'P':
  31. pfd.events = POLLPRI;
  32. break;
  33. case 't':
  34. timeout = atoi(optarg);
  35. break;
  36. default:
  37. fprintf(stderr, "Usage: %s [-I|-P] [-t timeout] FILE\n",
  38. argv[0]);
  39. return -1;
  40. }
  41. }
  42. if (optind >= argc) {
  43. fprintf(stderr, "Error: Polling file is not specified\n");
  44. return -1;
  45. }
  46. pfd.fd = open(argv[optind], O_RDONLY);
  47. if (pfd.fd < 0) {
  48. fprintf(stderr, "failed to open %s", argv[optind]);
  49. perror("open");
  50. return -1;
  51. }
  52. /* Reset poll by read if POLLIN is specified. */
  53. if (pfd.events & POLLIN)
  54. do {} while (read(pfd.fd, buf, BUFSIZE) == BUFSIZE);
  55. ret = poll(&pfd, 1, timeout);
  56. if (ret < 0 && errno != EINTR) {
  57. perror("poll");
  58. return -1;
  59. }
  60. close(pfd.fd);
  61. /* If timeout happned (ret == 0), exit code is 1 */
  62. if (ret == 0)
  63. return 1;
  64. return 0;
  65. }