1 #ifndef LIBSOCKET_SELECT_H_7F761B91E8A84EB685E898542039D68F 2 #define LIBSOCKET_SELECT_H_7F761B91E8A84EB685E898542039D68F 11 #include <sys/select.h> 13 #include <sys/types.h> 101 template <
typename SocketT>
104 std::map<int, SocketT*>
110 std::vector<poll::pollfd> pollfd_set;
115 void add_fd(
const SocketT& sock,
int method);
117 std::pair<std::vector<SocketT*>, std::vector<SocketT*> >
wait(
118 long long microsecs = 0);
119 typedef std::pair<std::vector<SocketT*>, std::vector<SocketT*> >
126 extern int highestfd(
const std::vector<int>& v);
133 template <
typename SockT>
145 template <
typename SocketT>
147 int fd = sock.getfd();
149 if (method == LIBSOCKET_READ) {
150 poll::pollfd fdinfo{fd, POLLIN, 0};
151 pollfd_set.push_back(fdinfo);
152 fdsockmap[fd] = const_cast<SocketT*>(&sock);
155 }
else if (method == LIBSOCKET_WRITE) {
156 poll::pollfd fdinfo{fd, POLLOUT, 0};
157 pollfd_set.push_back(fdinfo);
158 fdsockmap[fd] = const_cast<SocketT*>(&sock);
161 (LIBSOCKET_READ | LIBSOCKET_WRITE)) {
163 poll::pollfd fdinfo{fd, (POLLIN | POLLOUT), 0};
164 pollfd_set.push_back(fdinfo);
165 fdsockmap[fd] = const_cast<SocketT*>(&sock);
184 template <
typename SockT>
186 long long microsecs) {
189 struct timespec* timeout = NULL;
190 struct timespec _timeout;
192 if (microsecs != 0) {
195 long long nanosecs = microsecs * 1000;
196 long long nanopart = nanosecs % 1000000000;
197 long long secpart = (nanosecs - nanopart) / 1000000000;
199 _timeout.tv_sec = secpart;
200 _timeout.tv_nsec = nanopart;
203 n = ppoll((poll::pollfd*)pollfd_set.data(), pollfd_set.size(), timeout,
209 std::string err(strerror(errno));
212 "selectset::wait(): Error at ppoll(): " + err);
216 rwfds.first.resize(0);
217 rwfds.second.resize(0);
222 std::vector<poll::pollfd>::iterator end = pollfd_set.end();
224 for (std::vector<poll::pollfd>::iterator iter = pollfd_set.begin();
225 iter != end; ++iter) {
226 if (iter->revents & POLLIN) rwfds.first.push_back(fdsockmap[iter->fd]);
228 if (iter->revents & POLLOUT)
229 rwfds.second.push_back(fdsockmap[iter->fd]);
std::pair< std::vector< SocketT * >, std::vector< SocketT * > > wait(long long microsecs=0)
Waits for a possibility to read or write data to emerge.
Contains libsocket elements.
void add_fd(const SocketT &sock, int method)
Add a socket to the internal sets.
This class is instantiated and thrown when an error occurs. If there's an error somewhere in libsocke...
int highestfd(const std::vector< int > &v)
Utility function to find the highest number in a vector (typically, the highest file descriptor)
std::map< int, SocketT * > fdsockmap
bool set_up
Stores if the class has been initiated.
selectset provides a simple abstraction over – contrary to its name – poll(2).