src/util.{c,h}: fatal_error_free()
[vlock.git] / src / util.c
blob1fbd1f48dd835ccb8875daefb2bacf6e45aed029
1 /* util.c -- utility routines for vlock, the VT locking program for linux
3 * This program is copyright (C) 2007 Frank Benkstein, and is free
4 * software which is freely distributable under the terms of the
5 * GNU General Public License version 2, included as the file COPYING in this
6 * distribution. It is NOT public domain software, and any
7 * redistribution not permitted by the GNU General Public License is
8 * expressly forbidden without prior written permission from
9 * the author.
13 #if !defined(__FreeBSD__) && !defined(_GNU_SOURCE)
14 #define _GNU_SOURCE
15 #endif
17 #include <stdlib.h>
18 #include <stdarg.h>
19 #include <stdio.h>
20 #include <time.h>
22 #include "util.h"
24 /* Parse the given string (interpreted as seconds) into a
25 * timespec. On error NULL is returned. The caller is responsible
26 * to free the result. The string may be NULL, in which case NULL
27 * is returned, too. */
28 struct timespec *parse_seconds(const char *s)
30 if (s == NULL) {
31 return NULL;
32 } else {
33 char *n;
34 struct timespec *t = calloc(sizeof *t, 1);
36 if (t == NULL)
37 return NULL;
39 t->tv_sec = strtol(s, &n, 10);
41 if (*n != '\0' || t->tv_sec <= 0) {
42 free(t);
43 t = NULL;
46 return t;
50 void fatal_error(const char *format, ...)
52 char *error;
53 va_list ap;
54 va_start(ap, format);
55 if (vasprintf(&error, format, ap) < 0)
56 error = "error while formatting error message";
57 va_end(ap);
58 fatal_error_free(error);
61 void fatal_error_free(char *error)
63 fputs(error, stderr);
64 fputc('\n', stderr);
65 abort();
68 void *ensure_malloc(size_t size)
70 void *r = malloc(size);
72 if (r == NULL)
73 fatal_error("failed to allocate %d bytes", size);
75 return r;
78 void *ensure_calloc(size_t number, size_t size)
80 void *r = calloc(number, size);
82 if (r == NULL)
83 fatal_error("failed to allocate %d bytes", size);
85 return r;
88 void *ensure_realloc(void *ptr, size_t size)
90 void *r = realloc(ptr, size);
92 if (size != 0 && r == NULL)
93 fatal_error("failed to reallocate %d bytes at %p", size, ptr);
95 return r;
98 void *ensure_not_null(void *data, const char *errmsg)
100 if (data == NULL)
101 fatal_error(errmsg);
103 return data;