src/util.{c,h}: fatal_perror
[vlock.git] / src / util.c
blobc94b67b9ad30fbc6a1508b39cd8971c5927ebac3
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 <string.h>
21 #include <errno.h>
22 #include <time.h>
24 #include "util.h"
26 /* Parse the given string (interpreted as seconds) into a
27 * timespec. On error NULL is returned. The caller is responsible
28 * to free the result. The string may be NULL, in which case NULL
29 * is returned, too. */
30 struct timespec *parse_seconds(const char *s)
32 if (s == NULL) {
33 return NULL;
34 } else {
35 char *n;
36 struct timespec *t = calloc(sizeof *t, 1);
38 if (t == NULL)
39 return NULL;
41 t->tv_sec = strtol(s, &n, 10);
43 if (*n != '\0' || t->tv_sec <= 0) {
44 free(t);
45 t = NULL;
48 return t;
52 void fatal_error(const char *format, ...)
54 char *error;
55 va_list ap;
56 va_start(ap, format);
57 if (vasprintf(&error, format, ap) < 0)
58 error = "error while formatting error message";
59 va_end(ap);
60 fatal_error_free(error);
63 void fatal_error_free(char *error)
65 fputs(error, stderr);
66 fputc('\n', stderr);
67 free(error);
68 abort();
71 void fatal_perror(const char *errmsg)
73 if (errno != 0)
74 fatal_error("%s: %s", errmsg, strerror(errno));
75 else
76 fatal_error("%s", errmsg);
79 void *ensure_malloc(size_t size)
81 void *r = malloc(size);
83 if (r == NULL)
84 fatal_error("failed to allocate %d bytes", size);
86 return r;
89 void *ensure_calloc(size_t number, size_t size)
91 void *r = calloc(number, size);
93 if (r == NULL)
94 fatal_error("failed to allocate %d bytes", size);
96 return r;
99 void *ensure_realloc(void *ptr, size_t size)
101 void *r = realloc(ptr, size);
103 if (size != 0 && r == NULL)
104 fatal_error("failed to reallocate %d bytes at %p", size, ptr);
106 return r;
109 void *ensure_not_null(void *data, const char *errmsg)
111 if (data == NULL)
112 fatal_error(errmsg);
114 return data;