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 2, 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>
32 # ifdef HAVE_SYS_SELECT_H
33 # include <sys/select.h>
35 # ifdef HAVE_SYS_TIME_H
36 # include <sys/time.h>
38 # ifdef HAVE_SYS_TYPES_H
39 # include <sys/types.h>
48 static gr_dispatcher_sptr s_singleton;
53 return gr_dispatcher_sptr(new gr_dispatcher());
57 gr_dispatcher_singleton()
62 s_singleton = gr_make_dispatcher();
66 #if !defined(HAVE_SELECT) // Stub it out
68 gr_dispatcher::gr_dispatcher()
72 gr_dispatcher::~gr_dispatcher()
77 gr_dispatcher::add_handler(gr_select_handler_sptr handler)
83 gr_dispatcher::del_handler(gr_select_handler_sptr handler)
89 gr_dispatcher::del_handler(gr_select_handler *handler)
95 gr_dispatcher::loop(double timeout)
99 #else // defined(HAVE_SELECT)
101 gr_dispatcher::gr_dispatcher()
102 : d_handler(FD_SETSIZE), d_max_index(-1)
106 gr_dispatcher::~gr_dispatcher()
111 gr_dispatcher::add_handler(gr_select_handler_sptr handler)
113 int fd = handler->fd();
114 if (fd < 0 || fd >= FD_SETSIZE)
117 d_max_index = std::max(d_max_index, fd);
118 d_handler[fd] = handler;
123 gr_dispatcher::del_handler(gr_select_handler_sptr handler)
125 return del_handler(handler.get());
129 gr_dispatcher::del_handler(gr_select_handler *handler)
131 int fd = handler->fd();
132 if (fd < 0 || fd >= FD_SETSIZE)
135 d_handler[fd].reset();
137 if (fd == d_max_index){
139 for (i = fd - 1; i >= 0 && !d_handler[i]; i--)
148 gr_dispatcher::loop(double timeout)
150 struct timeval master;
155 double secs = floor (timeout);
156 master.tv_sec = (long) secs;
157 master.tv_usec = (long) ((timeout - secs) * 1e6);
159 while (d_max_index >= 0){
163 for (int i = 0; i <= d_max_index; i++){
164 if (d_handler[i] && d_handler[i]->readable())
166 if (d_handler[i] && d_handler[i]->writable())
171 int retval = select(d_max_index+1, &rd_set, &wr_set, 0, &tmp);
172 if (retval == 0) // timed out with nothing ready
177 perror ("gr_dispatcher/select");
181 for (int i = 0; i <= d_max_index; i++){
182 if (FD_ISSET(i, &rd_set))
184 d_handler[i]->handle_read();
185 if (FD_ISSET(i, &wr_set))
187 d_handler[i]->handle_write();