socket_epoll.h 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. #ifndef poll_socket_epoll_h
  2. #define poll_socket_epoll_h
  3. #include <netdb.h>
  4. #include <unistd.h>
  5. #include <sys/epoll.h>
  6. #include <sys/types.h>
  7. #include <sys/socket.h>
  8. #include <netinet/in.h>
  9. #include <arpa/inet.h>
  10. #include <fcntl.h>
  11. static bool
  12. sp_invalid(int efd) {
  13. return efd == -1;
  14. }
  15. static int
  16. sp_create() {
  17. return epoll_create(1024);
  18. }
  19. static void
  20. sp_release(int efd) {
  21. close(efd);
  22. }
  23. static int
  24. sp_add(int efd, int sock, void *ud) {
  25. struct epoll_event ev;
  26. ev.events = EPOLLIN;
  27. ev.data.ptr = ud;
  28. if (epoll_ctl(efd, EPOLL_CTL_ADD, sock, &ev) == -1) {
  29. return 1;
  30. }
  31. return 0;
  32. }
  33. static void
  34. sp_del(int efd, int sock) {
  35. epoll_ctl(efd, EPOLL_CTL_DEL, sock , NULL);
  36. }
  37. static int
  38. sp_enable(int efd, int sock, void *ud, bool read_enable, bool write_enable) {
  39. struct epoll_event ev;
  40. ev.events = (read_enable ? EPOLLIN : 0) | (write_enable ? EPOLLOUT : 0);
  41. ev.data.ptr = ud;
  42. if (epoll_ctl(efd, EPOLL_CTL_MOD, sock, &ev) == -1) {
  43. return 1;
  44. }
  45. return 0;
  46. }
  47. static int
  48. sp_wait(int efd, struct event *e, int max) {
  49. struct epoll_event ev[max];
  50. int n = epoll_wait(efd , ev, max, -1);
  51. int i;
  52. for (i=0;i<n;i++) {
  53. e[i].s = ev[i].data.ptr;
  54. unsigned flag = ev[i].events;
  55. e[i].write = (flag & EPOLLOUT) != 0;
  56. e[i].read = (flag & EPOLLIN) != 0;
  57. e[i].error = (flag & EPOLLERR) != 0;
  58. e[i].eof = (flag & EPOLLHUP) != 0;
  59. }
  60. return n;
  61. }
  62. static void
  63. sp_nonblocking(int fd) {
  64. int flag = fcntl(fd, F_GETFL, 0);
  65. if ( -1 == flag ) {
  66. return;
  67. }
  68. fcntl(fd, F_SETFL, flag | O_NONBLOCK);
  69. }
  70. #endif