/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 | | Licensed under the Apache License, Version 2.0 (the "License"); |
7 | | you may not use this file except in compliance with the License. |
8 | | You may obtain a copy of the License at |
9 | | |
10 | | http://www.apache.org/licenses/LICENSE-2.0 |
11 | | |
12 | | Unless required by applicable law or agreed to in writing, software |
13 | | distributed under the License is distributed on an "AS IS" BASIS, |
14 | | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
15 | | See the License for the specific language governing permissions and |
16 | | limitations under the License. |
17 | | |
18 | | To the extent this program is licensed as part of the Enterprise |
19 | | versions of CFEngine, the applicable Commercial Open Source License |
20 | | (COSL) may apply to this file if you as a licensee so wish it. See |
21 | | included file COSL.txt. |
22 | | */ |
23 | | |
24 | | #include <alloc.h> |
25 | | #include <cleanup.h> |
26 | | #include <platform.h> |
27 | | |
28 | | typedef struct CleanupList |
29 | | { |
30 | | CleanupFn fn; |
31 | | struct CleanupList *next; |
32 | | } CleanupList; |
33 | | |
34 | | static pthread_mutex_t cleanup_functions_mutex = PTHREAD_MUTEX_INITIALIZER; |
35 | | static CleanupList *cleanup_functions; |
36 | | |
37 | | /* To be called externally only by Windows binaries */ |
38 | | void CallCleanupFunctions(void) |
39 | 0 | { |
40 | 0 | pthread_mutex_lock(&cleanup_functions_mutex); |
41 | |
|
42 | 0 | CleanupList *p = cleanup_functions; |
43 | 0 | while (p) |
44 | 0 | { |
45 | 0 | CleanupList *cur = p; |
46 | 0 | (cur->fn)(); |
47 | 0 | p = cur->next; |
48 | 0 | free(cur); |
49 | 0 | } |
50 | |
|
51 | 0 | cleanup_functions = NULL; |
52 | |
|
53 | 0 | pthread_mutex_unlock(&cleanup_functions_mutex); |
54 | 0 | } |
55 | | |
56 | | void DoCleanupAndExit(int ret) |
57 | 0 | { |
58 | 0 | CallCleanupFunctions(); |
59 | 0 | exit(ret); |
60 | 0 | } |
61 | | |
62 | | void RegisterCleanupFunction(CleanupFn fn) |
63 | 0 | { |
64 | 0 | pthread_mutex_lock(&cleanup_functions_mutex); |
65 | |
|
66 | 0 | CleanupList *p = xmalloc(sizeof(CleanupList)); |
67 | 0 | p->fn = fn; |
68 | 0 | p->next = cleanup_functions; |
69 | |
|
70 | 0 | cleanup_functions = p; |
71 | |
|
72 | 0 | pthread_mutex_unlock(&cleanup_functions_mutex); |
73 | 0 | } |
74 | | |