poll.c 845 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. #define _XOPEN_SOURCE 700
  2. #include <assert.h>
  3. #include <fcntl.h> /* creat, O_CREAT */
  4. #include <poll.h> /* poll */
  5. #include <stdio.h> /* printf, puts, snprintf */
  6. #include <stdlib.h> /* EXIT_FAILURE, EXIT_SUCCESS */
  7. #include <unistd.h> /* read */
  8. int main(int argc, char **argv) {
  9. char buf[1024];
  10. int fd, i, n;
  11. short revents;
  12. struct pollfd pfd;
  13. if (argc < 2) {
  14. fprintf(stderr, "usage: %s <poll-device>\n", argv[0]);
  15. exit(EXIT_FAILURE);
  16. }
  17. fd = open(argv[1], O_RDONLY | O_NONBLOCK);
  18. if (fd == -1) {
  19. perror("open");
  20. exit(EXIT_FAILURE);
  21. }
  22. pfd.fd = fd;
  23. pfd.events = POLLIN;
  24. while (1) {
  25. puts("loop");
  26. i = poll(&pfd, 1, -1);
  27. if (i == -1) {
  28. perror("poll");
  29. assert(0);
  30. }
  31. revents = pfd.revents;
  32. if (revents & POLLIN) {
  33. n = read(pfd.fd, buf, sizeof(buf));
  34. printf("POLLIN n=%d buf=%.*s\n", n, n, buf);
  35. }
  36. }
  37. }