poll_many_types.c 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #include <errno.h>
  2. #include <fcntl.h>
  3. #include <poll.h>
  4. #include <stdio.h>
  5. #include <string.h>
  6. #include <sys/stat.h>
  7. #include <sys/types.h>
  8. #include <unistd.h>
  9. int main(int argc, char** argv) {
  10. int ret;
  11. char string[] = "Hello, world!\n";
  12. /* type 1: pipe */
  13. int pipefd[2];
  14. ret = pipe(pipefd);
  15. if (ret < 0) {
  16. perror("pipe creation");
  17. return 1;
  18. }
  19. /* write something into write end of pipe so read end becomes pollable */
  20. ssize_t written = 0;
  21. while (written < sizeof(string)) {
  22. ssize_t n;
  23. if ((n = write(pipefd[1], string + written, sizeof(string) - written)) < 0) {
  24. if (errno == EINTR || errno == EAGAIN)
  25. continue;
  26. perror("pipe write");
  27. return 1;
  28. }
  29. written += n;
  30. }
  31. /* type 2: regular file */
  32. int filefd = open(argv[0], O_RDONLY);
  33. if (filefd < 0) {
  34. perror("file open");
  35. return 1;
  36. }
  37. /* type 3: dev file */
  38. int devfd = open("/dev/urandom", O_RDONLY);
  39. if (devfd < 0) {
  40. perror("dev/urandom open");
  41. return 1;
  42. }
  43. struct pollfd infds[] = {
  44. {.fd = pipefd[0], .events = POLLIN},
  45. {.fd = filefd, .events = POLLIN},
  46. {.fd = devfd, .events = POLLIN},
  47. };
  48. ret = poll(infds, 3, -1);
  49. if (ret <= 0) {
  50. perror("poll with POLLIN");
  51. return 1;
  52. }
  53. printf("poll(POLLIN) returned %d file descriptors\n", ret);
  54. return 0;
  55. }