poll.c 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. // Copyright 2019-2020 Espressif Systems (Shanghai) PTE LTD
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. #include <stddef.h>
  15. #include <sys/poll.h>
  16. #include <sys/select.h>
  17. #include <sys/errno.h>
  18. #include <sys/param.h>
  19. int poll(struct pollfd *fds, nfds_t nfds, int timeout)
  20. {
  21. struct timeval tv = {
  22. // timeout is in milliseconds
  23. .tv_sec = timeout / 1000,
  24. .tv_usec = (timeout % 1000) * 1000,
  25. };
  26. int max_fd = -1;
  27. fd_set readfds;
  28. fd_set writefds;
  29. fd_set errorfds;
  30. struct _reent* r = __getreent();
  31. int ret = 0;
  32. if (fds == NULL) {
  33. __errno_r(r) = ENOENT;
  34. return -1;
  35. }
  36. FD_ZERO(&readfds);
  37. FD_ZERO(&writefds);
  38. FD_ZERO(&errorfds);
  39. for (unsigned int i = 0; i < nfds; ++i) {
  40. fds[i].revents = 0;
  41. if (fds[i].fd < 0) {
  42. // revents should remain 0 and events ignored (according to the documentation of poll()).
  43. continue;
  44. }
  45. if (fds[i].fd >= FD_SETSIZE) {
  46. fds[i].revents |= POLLNVAL;
  47. ++ret;
  48. continue;
  49. }
  50. if (fds[i].events & (POLLIN | POLLRDNORM | POLLRDBAND | POLLPRI)) {
  51. FD_SET(fds[i].fd, &readfds);
  52. FD_SET(fds[i].fd, &errorfds);
  53. max_fd = MAX(max_fd, fds[i].fd);
  54. }
  55. if (fds[i].events & (POLLOUT | POLLWRNORM | POLLWRBAND)) {
  56. FD_SET(fds[i].fd, &writefds);
  57. FD_SET(fds[i].fd, &errorfds);
  58. max_fd = MAX(max_fd, fds[i].fd);
  59. }
  60. }
  61. const int select_ret = select(max_fd + 1, &readfds, &writefds, &errorfds, timeout < 0 ? NULL: &tv);
  62. if (select_ret > 0) {
  63. ret += select_ret;
  64. for (unsigned int i = 0; i < nfds; ++i) {
  65. if (FD_ISSET(fds[i].fd, &readfds)) {
  66. fds[i].revents |= POLLIN;
  67. }
  68. if (FD_ISSET(fds[i].fd, &writefds)) {
  69. fds[i].revents |= POLLOUT;
  70. }
  71. if (FD_ISSET(fds[i].fd, &errorfds)) {
  72. fds[i].revents |= POLLERR;
  73. }
  74. }
  75. } else {
  76. ret = select_ret;
  77. // keeping the errno from select()
  78. }
  79. return ret;
  80. }