fakepoll.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /*
  2. * fakepoll.c
  3. *
  4. * On systems where 'poll' doesn't exist, fake it with 'select'.
  5. *
  6. * Nick Mathewson <nickm@freehaven.net>
  7. */
  8. #include "orconfig.h"
  9. #include "fakepoll.h"
  10. #ifdef USE_FAKE_POLL
  11. #include <sys/types.h>
  12. #ifdef HAVE_UNISTD_H
  13. #include <unistd.h>
  14. #endif
  15. #ifdef HAVE_STRING_H
  16. #include <string.h>
  17. #endif
  18. #if _MSC_VER > 1300
  19. #include <winsock2.h>
  20. #include <ws2tcpip.h>
  21. #elif defined(_MSC_VER)
  22. #include <winsock.h>
  23. #endif
  24. #include "util.h"
  25. int
  26. poll(struct pollfd *ufds, unsigned int nfds, int timeout)
  27. {
  28. unsigned int idx, maxfd, fd;
  29. int r;
  30. #ifdef MS_WINDOWS
  31. int any_fds_set = 0;
  32. #endif
  33. fd_set readfds, writefds, exceptfds;
  34. #ifdef USING_FAKE_TIMEVAL
  35. #undef timeval
  36. #undef tv_sec
  37. #undef tv_usec
  38. #endif
  39. struct timeval _timeout;
  40. _timeout.tv_sec = timeout/1000;
  41. _timeout.tv_usec = (timeout%1000)*1000;
  42. FD_ZERO(&readfds);
  43. FD_ZERO(&writefds);
  44. FD_ZERO(&exceptfds);
  45. maxfd = -1;
  46. for (idx = 0; idx < nfds; ++idx) {
  47. fd = ufds[idx].fd;
  48. if (ufds[idx].events) {
  49. if (fd > maxfd)
  50. maxfd = fd;
  51. #ifdef MS_WINDOWS
  52. any_fds_set = 1;
  53. #endif
  54. }
  55. if (ufds[idx].events & POLLIN)
  56. FD_SET(fd, &readfds);
  57. if (ufds[idx].events & POLLOUT)
  58. FD_SET(fd, &writefds);
  59. if (ufds[idx].events & POLLERR)
  60. FD_SET(fd, &exceptfds);
  61. }
  62. #ifdef MS_WINDOWS
  63. if (!any_fds_set) {
  64. Sleep(timeout);
  65. return 0;
  66. }
  67. #endif
  68. r = select(maxfd+1, &readfds, &writefds, &exceptfds,
  69. timeout == -1 ? NULL : &_timeout);
  70. if (r <= 0)
  71. return r;
  72. r = 0;
  73. for (idx = 0; idx < nfds; ++idx) {
  74. fd = ufds[idx].fd;
  75. ufds[idx].revents = 0;
  76. if (FD_ISSET(fd, &readfds))
  77. ufds[idx].revents |= POLLIN;
  78. if (FD_ISSET(fd, &writefds))
  79. ufds[idx].revents |= POLLOUT;
  80. if (FD_ISSET(fd, &exceptfds))
  81. ufds[idx].revents |= POLLERR;
  82. if (ufds[idx].revents)
  83. ++r;
  84. }
  85. return r;
  86. }
  87. #endif