2 fd.c -- I/O and event multiplexing
4 Copyright (C) 2003-2004 Guus Sliepen <guus@tinc-vpn.org>,
6 This program is free software; you can redistribute it and/or modify
7 it under the terms of the GNU General Public License as published by
8 the Free Software Foundation; either version 2 of the License, or
9 (at your option) any later version.
11 This program is distributed in the hope that it will be useful,
12 but WITHOUT ANY WARRANTY; without even the implied warranty of
13 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 GNU General Public License for more details.
16 You should have received a copy of the GNU General Public License
17 along with this program; if not, write to the Free Software
18 Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
25 #include "support/avl.h"
26 #include "support/xalloc.h"
30 static fd_set fd_sets[FD_MODES];
32 static avl_tree_t *fds;
34 volatile bool fd_running = false;
36 int fd_compare(struct fd *a, struct fd *b) {
37 return (a->fd - b->fd) ?: (a->mode - b->mode);
43 for(i = 0; i < FD_MODES; i++)
46 fds = avl_tree_new((avl_compare_t)fd_compare, NULL);
57 bool fd_add(struct fd *fd) {
61 FD_SET(fd->fd, &fd_sets[fd->mode]);
69 bool fd_del(struct fd *fd) {
70 FD_CLR(fd->fd, &fd_sets[fd->mode]);
73 max_fd = ((struct fd *)fds->tail)->fd;
75 return avl_del(fds, fd);
81 fd_set fd_cur[FD_MODES];
85 logger(LOG_INFO, "fd: running");
88 memcpy(fd_cur, fd_sets, sizeof(fd_cur));
91 result = select(max_fd + 1, &fd_cur[0], &fd_cur[1], &fd_cur[2], tv.tv_sec >= 0 ? &tv : NULL);
94 if(errno != EINTR && errno != EAGAIN) {
95 logger(LOG_ERR, _("fd: error while waiting for input: %s"), strerror(errno));
105 avl_foreach(fds, fd, {
106 if(FD_ISSET(fd->fd, &fd_cur[fd->mode]))
114 logger(LOG_INFO, "fd: stopping");