epoll.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. #include <errno.h>
  2. #include <fcntl.h>
  3. #include <stdio.h>
  4. #include <stdlib.h>
  5. #include <string.h>
  6. #include <sys/epoll.h>
  7. #include <unistd.h>
  8. #define TEST_TIMES 4
  9. int main(int argc, char** argv) {
  10. int ret = 0;
  11. int fds[TEST_TIMES][2];
  12. int efd = epoll_create(TEST_TIMES);
  13. if (efd < 0) {
  14. perror("epoll_create");
  15. exit(1);
  16. }
  17. struct epoll_event event;
  18. for (int i = 0; i < TEST_TIMES; i++) {
  19. ret = pipe(fds[i]);
  20. if (ret < 0) {
  21. perror("pipe");
  22. exit(1);
  23. }
  24. event.events = EPOLLIN;
  25. event.data.fd = fds[i][0];
  26. ret = epoll_ctl(efd, EPOLL_CTL_ADD, fds[i][0], &event);
  27. if (ret < 0) {
  28. perror("epoll_ctl add");
  29. exit(1);
  30. }
  31. }
  32. ret = fork();
  33. if (ret < 0) {
  34. perror("fork");
  35. exit(1);
  36. }
  37. if (!ret) {
  38. for (int i = 0; i < TEST_TIMES; i++) {
  39. close(fds[i][0]);
  40. char c = 0;
  41. if (write(fds[i][1], &c, 1) != 1) {
  42. perror("write error");
  43. exit(1);
  44. }
  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. }
  52. for (int i = 0; i < TEST_TIMES; i++) {
  53. ret = epoll_wait(efd, &event, 1, -1);
  54. if (ret < 0) {
  55. perror("epoll_wait");
  56. exit(1);
  57. }
  58. if (!ret)
  59. break;
  60. if (event.events & EPOLLIN) {
  61. char c;
  62. if (read(event.data.fd, &c, 1) != 1) {
  63. perror("read error");
  64. exit(1);
  65. }
  66. }
  67. printf("fd %d polled:", event.data.fd);
  68. if (event.events & EPOLLIN)
  69. printf(" EPOLLIN");
  70. if (event.events & EPOLLERR)
  71. printf(" EPOLLERR");
  72. if (event.events & EPOLLHUP)
  73. printf(" EPOLLHUP");
  74. if (event.events & EPOLLRDHUP)
  75. printf(" EPOLLRDHUP");
  76. printf("\n");
  77. }
  78. return 0;
  79. }