chiark / gitweb /
first attempt at proper service/socket logic
[elogind.git] / util.h
1 /*-*- Mode: C; c-basic-offset: 8 -*-*/
2
3 #ifndef fooutilhfoo
4 #define fooutilhfoo
5
6 #include <inttypes.h>
7 #include <time.h>
8 #include <sys/time.h>
9 #include <stdbool.h>
10 #include <stdlib.h>
11
12 typedef uint64_t usec_t;
13
14 #define MSEC_PER_SEC  1000ULL
15 #define USEC_PER_SEC  1000000ULL
16 #define USEC_PER_MSEC 1000ULL
17 #define NSEC_PER_SEC  1000000000ULL
18 #define NSEC_PER_MSEC 1000000ULL
19 #define NSEC_PER_USEC 1000ULL
20
21 usec_t now(clockid_t clock);
22
23 usec_t timespec_load(const struct timespec *ts);
24 struct timespec *timespec_store(struct timespec *ts, usec_t u);
25
26 usec_t timeval_load(const struct timeval *tv);
27 struct timeval *timeval_store(struct timeval *tv, usec_t u);
28
29 #define streq(a,b) (strcmp((a),(b)) == 0)
30
31 #define new(t, n) ((t*) malloc(sizeof(t)*(n)))
32
33 #define new0(t, n) ((t*) calloc((n), sizeof(t)))
34
35 #define malloc0(n) (calloc((n), 1))
36
37 static inline const char* yes_no(bool b) {
38         return b ? "yes" : "no";
39 }
40
41 static inline const char* strempty(const char *s) {
42         return s ? s : "";
43 }
44
45 static inline const char* strnull(const char *s) {
46         return s ? s : "(null)";
47 }
48
49 static inline const char *strna(const char *s) {
50         return s ? s : "n/a";
51 }
52
53 static inline bool is_path_absolute(const char *p) {
54         return *p == '/';
55 }
56
57 bool endswith(const char *s, const char *postfix);
58 bool startswith(const char *s, const char *prefix);
59
60 int close_nointr(int fd);
61
62 int parse_boolean(const char *v);
63
64 int safe_atou(const char *s, unsigned *ret_u);
65 int safe_atoi(const char *s, int *ret_i);
66
67 int safe_atolu(const char *s, unsigned long *ret_u);
68 int safe_atoli(const char *s, long int *ret_i);
69
70 int safe_atollu(const char *s, unsigned long long *ret_u);
71 int safe_atolli(const char *s, long long int *ret_i);
72
73 char *split_spaces(const char *c, size_t *l, char **state);
74 char *split_quoted(const char *c, size_t *l, char **state);
75
76 #define FOREACH_WORD(word, length, s, state)                            \
77         for ((state) = NULL, (word) = split_spaces((s), &(l), &(state)); (word); (word) = split_spaces((s), &(l), &(state)))
78
79 #define FOREACH_WORD_QUOTED(word, length, s, state)                     \
80         for ((state) = NULL, (word) = split_quoted((s), &(l), &(state)); (word); (word) = split_quoted((s), &(l), &(state)))
81
82 const char *sigchld_code(int code);
83
84 pid_t get_parent_of_pid(pid_t pid, pid_t *ppid);
85
86 int write_one_line_file(const char *fn, const char *line);
87 int read_one_line_file(const char *fn, char **line);
88
89 #endif