Branch data Line data Source code
1 : : /*
2 : : * Copyright (C) 2010-2015 Joel Rosdahl
3 : : *
4 : : * This program is free software; you can redistribute it and/or modify it
5 : : * under the terms of the GNU General Public License as published by the Free
6 : : * Software Foundation; either version 3 of the License, or (at your option)
7 : : * any later version.
8 : : *
9 : : * This program is distributed in the hope that it will be useful, but WITHOUT
10 : : * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 : : * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
12 : : * more details.
13 : : *
14 : : * You should have received a copy of the GNU General Public License along with
15 : : * this program; if not, write to the Free Software Foundation, Inc., 51
16 : : * Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17 : : */
18 : :
19 : : #include "ccache.h"
20 : :
21 : : struct exit_function {
22 : : void (*function)(void *);
23 : : void *context;
24 : : struct exit_function *next;
25 : : };
26 : :
27 : : struct nullary_exit_function {
28 : : void (*function)(void);
29 : : };
30 : :
31 : : static struct exit_function *exit_functions;
32 : :
33 : : static void
34 : 14 : call_nullary_exit_function(void *context)
35 : : {
36 : 14 : struct nullary_exit_function *p = (struct nullary_exit_function*)context;
37 : 14 : p->function();
38 : 14 : free(p);
39 : 14 : }
40 : :
41 : : /*
42 : : * Initialize exit functions. Must be called once before exitfn_add* are used.
43 : : */
44 : : void
45 : 7 : exitfn_init(void)
46 : : {
47 [ - + ]: 7 : if (atexit(exitfn_call) != 0) {
48 : 0 : fatal("atexit failed: %s", strerror(errno));
49 : : }
50 : 7 : }
51 : :
52 : : /*
53 : : * Add a nullary function to be called when ccache exits. Functions are called
54 : : * in reverse order.
55 : : */
56 : : void
57 : 14 : exitfn_add_nullary(void (*function)(void))
58 : : {
59 : 14 : struct nullary_exit_function *p = x_malloc(sizeof(*p));
60 : 14 : p->function = function;
61 : 14 : exitfn_add(call_nullary_exit_function, p);
62 : 14 : }
63 : :
64 : : /*
65 : : * Add a function to be called with a context parameter when ccache exits.
66 : : * Functions are called in reverse order.
67 : : */
68 : : void
69 : 14 : exitfn_add(void (*function)(void *), void *context)
70 : : {
71 : : struct exit_function *p;
72 : :
73 : 14 : p = x_malloc(sizeof(*p));
74 : 14 : p->function = function;
75 : 14 : p->context = context;
76 : 14 : p->next = exit_functions;
77 : 14 : exit_functions = p;
78 : 14 : }
79 : :
80 : : /*
81 : : * Call added functions.
82 : : */
83 : : void
84 : 7 : exitfn_call(void)
85 : : {
86 : 7 : struct exit_function *p = exit_functions, *q;
87 : 7 : exit_functions = NULL;
88 [ + + ]: 21 : while (p) {
89 : 14 : p->function(p->context);
90 : 14 : q = p;
91 : 14 : p = p->next;
92 : 14 : free(q);
93 : : }
94 : 7 : }
|