socket_kqueue.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. #ifndef poll_socket_kqueue_h
  2. #define poll_socket_kqueue_h
  3. #include <netdb.h>
  4. #include <unistd.h>
  5. #include <fcntl.h>
  6. #include <sys/event.h>
  7. #include <sys/types.h>
  8. #include <sys/socket.h>
  9. #include <netinet/in.h>
  10. #include <arpa/inet.h>
  11. static bool
  12. sp_invalid(int kfd) {
  13. return kfd == -1;
  14. }
  15. static int
  16. sp_create() {
  17. return kqueue();
  18. }
  19. static void
  20. sp_release(int kfd) {
  21. close(kfd);
  22. }
  23. static void
  24. sp_del(int kfd, int sock) {
  25. struct kevent ke;
  26. EV_SET(&ke, sock, EVFILT_READ, EV_DELETE, 0, 0, NULL);
  27. kevent(kfd, &ke, 1, NULL, 0, NULL);
  28. EV_SET(&ke, sock, EVFILT_WRITE, EV_DELETE, 0, 0, NULL);
  29. kevent(kfd, &ke, 1, NULL, 0, NULL);
  30. }
  31. static int
  32. sp_add(int kfd, int sock, void *ud) {
  33. struct kevent ke;
  34. EV_SET(&ke, sock, EVFILT_READ, EV_ADD, 0, 0, ud);
  35. if (kevent(kfd, &ke, 1, NULL, 0, NULL) == -1 || ke.flags & EV_ERROR) {
  36. return 1;
  37. }
  38. EV_SET(&ke, sock, EVFILT_WRITE, EV_ADD, 0, 0, ud);
  39. if (kevent(kfd, &ke, 1, NULL, 0, NULL) == -1 || ke.flags & EV_ERROR) {
  40. EV_SET(&ke, sock, EVFILT_READ, EV_DELETE, 0, 0, NULL);
  41. kevent(kfd, &ke, 1, NULL, 0, NULL);
  42. return 1;
  43. }
  44. EV_SET(&ke, sock, EVFILT_WRITE, EV_DISABLE, 0, 0, ud);
  45. if (kevent(kfd, &ke, 1, NULL, 0, NULL) == -1 || ke.flags & EV_ERROR) {
  46. sp_del(kfd, sock);
  47. return 1;
  48. }
  49. return 0;
  50. }
  51. static int
  52. sp_enable(int kfd, int sock, void *ud, bool read_enable, bool write_enable) {
  53. int ret = 0;
  54. struct kevent ke;
  55. EV_SET(&ke, sock, EVFILT_READ, read_enable ? EV_ENABLE : EV_DISABLE, 0, 0, ud);
  56. if (kevent(kfd, &ke, 1, NULL, 0, NULL) == -1 || ke.flags & EV_ERROR) {
  57. ret |= 1;
  58. }
  59. EV_SET(&ke, sock, EVFILT_WRITE, write_enable ? EV_ENABLE : EV_DISABLE, 0, 0, ud);
  60. if (kevent(kfd, &ke, 1, NULL, 0, NULL) == -1 || ke.flags & EV_ERROR) {
  61. ret |= 1;
  62. }
  63. return ret;
  64. }
  65. static int
  66. sp_wait(int kfd, struct event *e, int max) {
  67. struct kevent ev[max];
  68. int n = kevent(kfd, NULL, 0, ev, max, NULL);
  69. int i;
  70. for (i=0;i<n;i++) {
  71. e[i].s = ev[i].udata;
  72. unsigned filter = ev[i].filter;
  73. bool eof = (ev[i].flags & EV_EOF) != 0;
  74. e[i].write = (filter == EVFILT_WRITE) && (!eof);
  75. e[i].read = (filter == EVFILT_READ);
  76. e[i].error = (ev[i].flags & EV_ERROR) != 0;
  77. e[i].eof = eof;
  78. }
  79. return n;
  80. }
  81. static void
  82. sp_nonblocking(int fd) {
  83. int flag = fcntl(fd, F_GETFL, 0);
  84. if ( -1 == flag ) {
  85. return;
  86. }
  87. fcntl(fd, F_SETFL, flag | O_NONBLOCK);
  88. }
  89. #endif