/src/core/libntech/libutils/cleanup.c
Line | Count | Source (jump to first uncovered line) |
1 | | /* |
2 | | Copyright 2023 Northern.tech AS |
3 | | |
4 | | This file is part of CFEngine 3 - written and maintained by Northern.tech AS. |
5 | | |
6 | | This program is free software; you can redistribute it and/or modify it |
7 | | under the terms of the GNU General Public License as published by the |
8 | | Free Software Foundation; version 3. |
9 | | |
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. |
14 | | |
15 | | You should have received a copy of the GNU General Public License |
16 | | along with this program; if not, write to the Free Software |
17 | | Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA |
18 | | |
19 | | To the extent this program is licensed as part of the Enterprise |
20 | | versions of CFEngine, the applicable Commercial Open Source License |
21 | | (COSL) may apply to this file if you as a licensee so wish it. See |
22 | | included file COSL.txt. |
23 | | */ |
24 | | |
25 | | #include <alloc.h> |
26 | | #include <cleanup.h> |
27 | | #include <platform.h> |
28 | | |
29 | | typedef struct CleanupList |
30 | | { |
31 | | CleanupFn fn; |
32 | | struct CleanupList *next; |
33 | | } CleanupList; |
34 | | |
35 | | static pthread_mutex_t cleanup_functions_mutex = PTHREAD_MUTEX_INITIALIZER; |
36 | | static CleanupList *cleanup_functions; |
37 | | |
38 | | /* To be called externally only by Windows binaries */ |
39 | | void CallCleanupFunctions(void) |
40 | 0 | { |
41 | 0 | pthread_mutex_lock(&cleanup_functions_mutex); |
42 | |
|
43 | 0 | CleanupList *p = cleanup_functions; |
44 | 0 | while (p) |
45 | 0 | { |
46 | 0 | CleanupList *cur = p; |
47 | 0 | (cur->fn)(); |
48 | 0 | p = cur->next; |
49 | 0 | free(cur); |
50 | 0 | } |
51 | |
|
52 | 0 | cleanup_functions = NULL; |
53 | |
|
54 | 0 | pthread_mutex_unlock(&cleanup_functions_mutex); |
55 | 0 | } |
56 | | |
57 | | void DoCleanupAndExit(int ret) |
58 | 0 | { |
59 | 0 | CallCleanupFunctions(); |
60 | 0 | exit(ret); |
61 | 0 | } |
62 | | |
63 | | void RegisterCleanupFunction(CleanupFn fn) |
64 | 0 | { |
65 | 0 | pthread_mutex_lock(&cleanup_functions_mutex); |
66 | |
|
67 | 0 | CleanupList *p = xmalloc(sizeof(CleanupList)); |
68 | 0 | p->fn = fn; |
69 | 0 | p->next = cleanup_functions; |
70 | |
|
71 | 0 | cleanup_functions = p; |
72 | |
|
73 | 0 | pthread_mutex_unlock(&cleanup_functions_mutex); |
74 | 0 | } |
75 | | |