2 event.c -- I/O, timeout, and event handling
3 Copyright (C) 2012-2022 Guus Sliepen <guus@tinc-vpn.org>
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
15 You should have received a copy of the GNU General Public License along
16 with this program; if not, write to the Free Software Foundation, Inc.,
17 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
26 static int io_compare(const io_t *a, const io_t *b) {
31 if(a->event < b->event) {
35 if(a->event > b->event) {
43 static int timeout_compare(const timeout_t *a, const timeout_t *b) {
45 timersub(&a->tv, &b->tv, &diff);
55 if(diff.tv_usec < 0) {
59 if(diff.tv_usec > 0) {
74 splay_tree_t io_tree = {.compare = (splay_compare_t)io_compare};
75 splay_tree_t timeout_tree = {.compare = (splay_compare_t)timeout_compare};
77 void timeout_add(timeout_t *timeout, timeout_cb_t cb, void *data, const struct timeval *tv) {
80 timeout->node.data = timeout;
82 timeout_set(timeout, tv);
85 void timeout_set(timeout_t *timeout, const struct timeval *tv) {
86 if(timerisset(&timeout->tv)) {
87 splay_unlink_node(&timeout_tree, &timeout->node);
91 gettimeofday(&now, NULL);
94 timeradd(&now, tv, &timeout->tv);
96 if(!splay_insert_node(&timeout_tree, &timeout->node)) {
101 void timeout_del(timeout_t *timeout) {
106 splay_unlink_node(&timeout_tree, &timeout->node);
108 timeout->tv = (struct timeval) {
113 struct timeval *timeout_execute(struct timeval *diff) {
114 gettimeofday(&now, NULL);
115 struct timeval *tv = NULL;
117 while(timeout_tree.head) {
118 timeout_t *timeout = timeout_tree.head->data;
119 timersub(&timeout->tv, &now, diff);
121 if(diff->tv_sec < 0) {
122 timeout->cb(timeout->data);
124 if(timercmp(&timeout->tv, &now, <)) {
125 timeout_del(timeout);