3 * Copyright 2005 Free Software Foundation, Inc.
5 * This file is part of GNU Radio
7 * GNU Radio is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3, or (at your option)
12 * GNU Radio is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with GNU Radio; see the file COPYING. If not, write to
19 * the Free Software Foundation, Inc., 51 Franklin Street,
20 * Boston, MA 02110-1301, USA.
27 #include <gr_dispatcher.h>
33 # ifdef HAVE_SYS_SELECT_H
34 # include <sys/select.h>
36 # ifdef HAVE_SYS_TIME_H
37 # include <sys/time.h>
39 # ifdef HAVE_SYS_TYPES_H
40 # include <sys/types.h>
49 static gr_dispatcher_sptr s_singleton;
54 return gr_dispatcher_sptr(new gr_dispatcher());
58 gr_dispatcher_singleton()
63 s_singleton = gr_make_dispatcher();
67 #if !defined(HAVE_SELECT) // Stub it out
69 gr_dispatcher::gr_dispatcher()
73 gr_dispatcher::~gr_dispatcher()
78 gr_dispatcher::add_handler(gr_select_handler_sptr handler)
84 gr_dispatcher::del_handler(gr_select_handler_sptr handler)
90 gr_dispatcher::del_handler(gr_select_handler *handler)
96 gr_dispatcher::loop(double timeout)
100 #else // defined(HAVE_SELECT)
102 gr_dispatcher::gr_dispatcher()
103 : d_handler(FD_SETSIZE), d_max_index(-1)
107 gr_dispatcher::~gr_dispatcher()
112 gr_dispatcher::add_handler(gr_select_handler_sptr handler)
114 int fd = handler->fd();
115 if (fd < 0 || fd >= FD_SETSIZE)
118 d_max_index = std::max(d_max_index, fd);
119 d_handler[fd] = handler;
124 gr_dispatcher::del_handler(gr_select_handler_sptr handler)
126 return del_handler(handler.get());
130 gr_dispatcher::del_handler(gr_select_handler *handler)
132 int fd = handler->fd();
133 if (fd < 0 || fd >= FD_SETSIZE)
136 d_handler[fd].reset();
138 if (fd == d_max_index){
140 for (i = fd - 1; i >= 0 && !d_handler[i]; i--)
149 gr_dispatcher::loop(double timeout)
151 struct timeval master;
156 double secs = floor (timeout);
157 master.tv_sec = (long) secs;
158 master.tv_usec = (long) ((timeout - secs) * 1e6);
160 while (d_max_index >= 0){
164 for (int i = 0; i <= d_max_index; i++){
165 if (d_handler[i] && d_handler[i]->readable())
167 if (d_handler[i] && d_handler[i]->writable())
172 int retval = select(d_max_index+1, &rd_set, &wr_set, 0, &tmp);
173 if (retval == 0) // timed out with nothing ready
178 perror ("gr_dispatcher/select");
182 for (int i = 0; i <= d_max_index; i++){
183 if (FD_ISSET(i, &rd_set))
185 d_handler[i]->handle_read();
186 if (FD_ISSET(i, &wr_set))
188 d_handler[i]->handle_write();