epoll.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /* -*- mode:c; c-file-style:"k&r"; c-basic-offset: 4; tab-width:4; indent-tabs-mode:nil; mode:auto-fill; fill-column:78; -*- */
  2. /* vim: set ts=4 sw=4 et tw=78 fo=cqt wm=0: */
  3. #include <unistd.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. #include <stdio.h>
  7. #include <sys/epoll.h>
  8. #include <fcntl.h>
  9. #include <errno.h>
  10. #define TEST_TIMES 4
  11. int main (int argc, char ** argv)
  12. {
  13. int ret = 0;
  14. int fds[TEST_TIMES][2];
  15. int efd = epoll_create(TEST_TIMES);
  16. if (efd < 0) {
  17. perror("epoll_create");
  18. exit(1);
  19. }
  20. struct epoll_event event;
  21. for (int i = 0 ; i < TEST_TIMES ; i++) {
  22. ret = pipe(fds[i]);
  23. if (ret < 0) {
  24. perror("pipe");
  25. exit(1);
  26. }
  27. event.events = EPOLLIN;
  28. event.data.fd = fds[i][0];
  29. ret = epoll_ctl(efd, EPOLL_CTL_ADD, fds[i][0], &event);
  30. if (ret < 0) {
  31. perror("epoll_ctl add");
  32. exit(1);
  33. }
  34. }
  35. ret = fork();
  36. if (ret < 0) {
  37. perror("fork");
  38. exit(1);
  39. }
  40. if (!ret) {
  41. for (int i = 0 ; i < TEST_TIMES ; i++) {
  42. close(fds[i][0]);
  43. char c = 0;
  44. write(fds[i][1], &c, 1);
  45. close(fds[i][1]);
  46. }
  47. exit(0);
  48. }
  49. for (int i = 0 ; i < TEST_TIMES ; i++)
  50. close(fds[i][1]);
  51. for (int i = 0 ; i < TEST_TIMES ; i++) {
  52. ret = epoll_wait(efd, &event, 1, -1);
  53. if (ret < 0) {
  54. perror("epoll_wait");
  55. exit(1);
  56. }
  57. if (!ret)
  58. break;
  59. if (event.events & EPOLLIN) {
  60. char c;
  61. read(event.data.fd, &c, 1);
  62. }
  63. printf("fd %d polled:", event.data.fd);
  64. if (event.events & EPOLLIN)
  65. printf(" EPOLLIN");
  66. if (event.events & EPOLLERR)
  67. printf(" EPOLLERR");
  68. if (event.events & EPOLLHUP)
  69. printf(" EPOLLHUP");
  70. if (event.events & EPOLLRDHUP)
  71. printf(" EPOLLRDHUP");
  72. printf("\n");
  73. }
  74. return 0;
  75. }