epoll.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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. write(fds[i][1], &c, 1);
  42. close(fds[i][1]);
  43. }
  44. exit(0);
  45. }
  46. for (int i = 0; i < TEST_TIMES; i++) {
  47. close(fds[i][1]);
  48. }
  49. for (int i = 0; i < TEST_TIMES; i++) {
  50. ret = epoll_wait(efd, &event, 1, -1);
  51. if (ret < 0) {
  52. perror("epoll_wait");
  53. exit(1);
  54. }
  55. if (!ret)
  56. break;
  57. if (event.events & EPOLLIN) {
  58. char c;
  59. read(event.data.fd, &c, 1);
  60. }
  61. printf("fd %d polled:", event.data.fd);
  62. if (event.events & EPOLLIN)
  63. printf(" EPOLLIN");
  64. if (event.events & EPOLLERR)
  65. printf(" EPOLLERR");
  66. if (event.events & EPOLLHUP)
  67. printf(" EPOLLHUP");
  68. if (event.events & EPOLLRDHUP)
  69. printf(" EPOLLRDHUP");
  70. printf("\n");
  71. }
  72. return 0;
  73. }