My Project
 All Data Structures Files Functions Variables Typedefs Enumerations Enumerator Macros Modules
soc_select.c
Go to the documentation of this file.
1 #include "soc_common.h"
2 #include <errno.h>
3 #include <poll.h>
4 #include <stdlib.h>
5 #include <sys/select.h>
6 
7 int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout)
8 {
9  struct pollfd *pollinfo;
10  nfds_t numfds = 0;
11  size_t i, j;
12  int rc, found;
13 
14  for(i = 0; i < nfds; ++i) {
15  if((readfds && FD_ISSET(i, readfds))
16  || (writefds && FD_ISSET(i, writefds))
17  || (exceptfds && FD_ISSET(i, exceptfds)))
18  ++numfds;
19  }
20 
21  pollinfo = (struct pollfd*)calloc(numfds, sizeof(struct pollfd));
22  if(pollinfo == NULL) {
23  SOCU_errno = ENOMEM;
24  return -1;
25  }
26 
27  for(i = 0, j = 0; i < nfds; ++i) {
28  if((readfds && FD_ISSET(i, readfds))
29  || (writefds && FD_ISSET(i, writefds))
30  || (exceptfds && FD_ISSET(i, exceptfds))) {
31  pollinfo[j].fd = i;
32  pollinfo[j].events = 0;
33  pollinfo[j].revents = 0;
34 
35  if(readfds && FD_ISSET(i, readfds))
36  pollinfo[j].events |= POLLIN;
37  if(writefds && FD_ISSET(i, writefds))
38  pollinfo[j].events |= POLLOUT;
39 
40  ++j;
41  }
42  }
43 
44  if(timeout)
45  rc = poll(pollinfo, numfds, timeout->tv_sec*1000 + timeout->tv_usec/1000);
46  else
47  rc = poll(pollinfo, numfds, -1);
48 
49  if(rc < 0) {
50  free(pollinfo);
51  return rc;
52  }
53 
54  for(i = 0, j = 0, rc = 0; i < nfds; ++i) {
55  found = 0;
56 
57  if((readfds && FD_ISSET(i, readfds))
58  || (writefds && FD_ISSET(i, writefds))
59  || (exceptfds && FD_ISSET(i, exceptfds))) {
60 
61  if(readfds && FD_ISSET(i, readfds)) {
62  if(pollinfo[j].events & (POLLIN|POLLHUP))
63  found = 1;
64  else
65  FD_CLR(i, readfds);
66  }
67 
68  if(writefds && FD_ISSET(i, writefds)) {
69  if(pollinfo[j].events & (POLLOUT|POLLHUP))
70  found = 1;
71  else
72  FD_CLR(i, writefds);
73  }
74 
75  if(exceptfds && FD_ISSET(i, exceptfds)) {
76  if(pollinfo[j].events & POLLERR)
77  found = 1;
78  else
79  FD_CLR(i, exceptfds);
80  }
81 
82  if(found) ++rc;
83  ++j;
84  }
85  }
86 
87  free(pollinfo);
88 
89  return rc;
90 }
#define POLLHUP
Definition: poll.h:10
int revents
Definition: poll.h:23
int SOCU_errno
Definition: soc_common.c:5
#define POLLERR
Definition: poll.h:9
#define POLLIN
Definition: poll.h:6
int fd
Definition: poll.h:21
int events
Definition: poll.h:22
Definition: poll.h:19
int select(int nfds, fd_set *readfds, fd_set *writefds, fd_set *exceptfds, struct timeval *timeout)
Definition: soc_select.c:7
int poll(struct pollfd *fds, nfds_t nfsd, int timeout)
Definition: soc_poll.c:4
#define POLLOUT
Definition: poll.h:8
u32 nfds_t
Definition: poll.h:17