home · contact · privacy
License everything (GPL).
[plomrogue] / src / common / rexit.c
1 /* src/common/rexit.c
2  *
3  * This file is part of PlomRogue. PlomRogue is licensed under the GPL version 3
4  * or any later version. For details on its copyright, license, and warranties,
5  * see the file NOTICE in the root directory of the PlomRogue source package.
6  */
7
8 #include "rexit.h"
9 #include <errno.h> /* global errno */
10 #include <stdint.h> /* uint16_t */
11 #include <stdio.h> /* printf(), perror(), sprintf() */
12 #include <stdlib.h> /* exit(), free(), EXIT_FAILURE */
13 #include <string.h> /* strlen() */
14 #include "try_malloc.h" /* try_malloc() */
15
16
17
18 void (* cleanup_func) ();
19
20
21
22 extern void set_cleanup_func(void (* f)())
23 {
24     cleanup_func = f;
25 }
26
27
28
29 extern void exit_err(int err, const char * msg)
30 {
31     if (0 == err)
32     {
33         return;
34     }
35     cleanup_func();
36     if (!msg)
37     {
38         msg = "Details unknown.";
39     }
40     printf("Aborted program due to error. %s\n", msg);
41     if (0 != errno)
42     {
43         perror("errno states");
44     }
45     exit(EXIT_FAILURE);
46 }
47
48
49
50 extern void exit_trouble(int err, const char * parent, const char * child)
51 {
52     char * p1 = "Trouble in ";
53     char * p2 = " with ";
54     char * p3 = ".";
55     uint16_t size = strlen(p1) + strlen(parent) + strlen(p2) + strlen(child)
56                     + strlen(p3) + 1;
57     char * msg = try_malloc(size, __func__);
58     int test = sprintf(msg, "%s%s%s%s%s", p1, parent, p2, child, p3);
59     exit_err(test < 0, "Trouble in exit_trouble with sprintf.");
60     exit_err(err, msg);
61     free(msg);
62 }