Remove pidfile when exitting.
[tinc] / src / event.c
1 /*
2     event.c -- event queue
3     Copyright (C) 2002-2003 Guus Sliepen <guus@sliepen.eu.org>,
4                   2002-2003 Ivo Timmermans <ivo@o2w.nl>
5
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.
10
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.
15
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.
19
20     $Id: event.c,v 1.1.4.11 2003/08/28 21:05:10 guus Exp $
21 */
22
23 #include "system.h"
24
25 #include "avl_tree.h"
26 #include "event.h"
27 #include "utils.h"
28 #include "xalloc.h"
29
30 avl_tree_t *event_tree;
31 extern time_t now;
32
33 int id;
34
35 static int event_compare(const event_t *a, const event_t *b)
36 {
37         if(a->time > b->time)
38                 return 1;
39
40         if(a->time < b->time)
41                 return -1;
42
43         return a->id - b->id;
44 }
45
46 void init_events(void)
47 {
48         cp();
49
50         event_tree = avl_alloc_tree((avl_compare_t) event_compare, NULL);
51 }
52
53 void exit_events(void)
54 {
55         cp();
56
57         avl_delete_tree(event_tree);
58 }
59
60 event_t *new_event(void)
61 {
62         cp();
63
64         return xmalloc_and_zero(sizeof(event_t));
65 }
66
67 void free_event(event_t *event)
68 {
69         cp();
70
71         free(event);
72 }
73
74 void event_add(event_t *event)
75 {
76         cp();
77
78         event->id = ++id;
79         avl_insert(event_tree, event);
80 }
81
82 void event_del(event_t *event)
83 {
84         cp();
85
86         avl_delete(event_tree, event);
87 }
88
89 event_t *get_expired_event(void)
90 {
91         event_t *event;
92
93         cp();
94
95         if(event_tree->head) {
96                 event = event_tree->head->data;
97
98                 if(event->time < now) {
99                         avl_delete(event_tree, event);
100                         return event;
101                 }
102         }
103
104         return NULL;
105 }