Merge in updated yatl.
[awesomized/libmemcached] / poll / poll.c
1 /* LibMemcached
2 * Copyright (C) 2010 Brian Aker, Trond Norbye
3 * All rights reserved.
4 *
5 * Use and distribution licensed under the BSD license. See
6 * the COPYING file in the parent directory for full text.
7 *
8 * Summary: Implementation of poll by using select
9 *
10 */
11 #include "mem_config.h"
12
13 #if defined(WIN32) || defined(__MINGW32__)
14 # include <winsock2.h>
15 # include <ws2tcpip.h>
16 #endif
17
18 #include <sys/time.h>
19 #include <strings.h>
20
21 #include "poll/poll.h"
22
23 int poll(struct pollfd fds[], nfds_t nfds, int tmo)
24 {
25 fd_set readfds, writefds, errorfds;
26 FD_ZERO(&readfds);
27 FD_ZERO(&writefds);
28 FD_ZERO(&errorfds);
29
30 int maxfd= 0;
31
32 for (nfds_t x= 0; x < nfds; ++x)
33 {
34 if (fds[x].events & (POLLIN | POLLOUT))
35 {
36 #ifndef WIN32
37 if (fds[x].fd > maxfd)
38 {
39 maxfd= fds[x].fd;
40 }
41 #endif
42 if (fds[x].events & POLLIN)
43 {
44 FD_SET(fds[x].fd, &readfds);
45 }
46 if (fds[x].events & POLLOUT)
47 {
48 FD_SET(fds[x].fd, &writefds);
49 }
50 }
51 }
52
53 struct timeval timeout= { .tv_sec = tmo / 1000,
54 .tv_usec= (tmo % 1000) * 1000 };
55 struct timeval *tp= &timeout;
56 if (tmo == -1)
57 {
58 tp= NULL;
59 }
60 int ret= select(maxfd + 1, &readfds, &writefds, &errorfds, tp);
61 if (ret <= 0)
62 {
63 return ret;
64 }
65
66 /* Iterate through all of them because I need to clear the revent map */
67 for (nfds_t x= 0; x < nfds; ++x)
68 {
69 fds[x].revents= 0;
70 if (FD_ISSET(fds[x].fd, &readfds))
71 {
72 fds[x].revents |= POLLIN;
73 }
74 if (FD_ISSET(fds[x].fd, &writefds))
75 {
76 fds[x].revents |= POLLOUT;
77 }
78 if (FD_ISSET(fds[x].fd, &errorfds))
79 {
80 fds[x].revents |= POLLERR;
81 }
82 }
83
84 return ret;
85 }