fakepoll.c 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. /* Copyright 2002,2003 Nick Mathewson, Roger Dingledine */
  2. /* See LICENSE for licensing information */
  3. /* $Id$ */
  4. /* On systems where 'poll' doesn't exist, fake it with 'select'. */
  5. #include "orconfig.h"
  6. #include "fakepoll.h"
  7. #ifdef USE_FAKE_POLL
  8. #include <sys/types.h>
  9. #ifdef HAVE_UNISTD_H
  10. #include <unistd.h>
  11. #endif
  12. #ifdef HAVE_STRING_H
  13. #include <string.h>
  14. #endif
  15. #if _MSC_VER > 1300
  16. #include <winsock2.h>
  17. #include <ws2tcpip.h>
  18. #elif defined(_MSC_VER)
  19. #include <winsock.h>
  20. #endif
  21. /* by default, windows handles only 64 fd's */
  22. #if defined(MS_WINDOWS) && !defined(FD_SETSIZE)
  23. #define FD_SETSIZE MAXCONNECTIONS
  24. #endif
  25. #include "util.h"
  26. int
  27. tor_poll(struct pollfd *ufds, unsigned int nfds, int timeout)
  28. {
  29. unsigned int idx;
  30. int maxfd, fd;
  31. int r;
  32. #ifdef MS_WINDOWS
  33. int any_fds_set = 0;
  34. #endif
  35. fd_set readfds, writefds, exceptfds;
  36. #ifdef USING_FAKE_TIMEVAL
  37. #undef timeval
  38. #undef tv_sec
  39. #undef tv_usec
  40. #endif
  41. struct timeval _timeout;
  42. _timeout.tv_sec = timeout/1000;
  43. _timeout.tv_usec = (timeout%1000)*1000;
  44. FD_ZERO(&readfds);
  45. FD_ZERO(&writefds);
  46. FD_ZERO(&exceptfds);
  47. maxfd = -1;
  48. for (idx = 0; idx < nfds; ++idx) {
  49. ufds[idx].revents = 0;
  50. fd = ufds[idx].fd;
  51. if (fd > maxfd) {
  52. maxfd = fd;
  53. #ifdef MS_WINDOWS
  54. any_fds_set = 1;
  55. #endif
  56. }
  57. if (ufds[idx].events & POLLIN)
  58. FD_SET(fd, &readfds);
  59. if (ufds[idx].events & POLLOUT)
  60. FD_SET(fd, &writefds);
  61. FD_SET(fd, &exceptfds);
  62. }
  63. #ifdef MS_WINDOWS
  64. if (!any_fds_set) {
  65. Sleep(timeout);
  66. return 0;
  67. }
  68. #endif
  69. r = select(maxfd+1, &readfds, &writefds, &exceptfds,
  70. timeout == -1 ? NULL : &_timeout);
  71. if (r <= 0)
  72. return r;
  73. r = 0;
  74. for (idx = 0; idx < nfds; ++idx) {
  75. fd = ufds[idx].fd;
  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