]> git.meshlink.io Git - catta/blob - util.c
* add todo list
[catta] / util.c
1 #include <string.h>
2 #include <unistd.h>
3 #include <fcntl.h>
4 #include <errno.h>
5
6 #include "util.h"
7
8 gchar *flx_get_host_name(void) {
9     char t[256];
10     gethostname(t, sizeof(t));
11     return g_strndup(t, sizeof(t));
12 }
13
14 gchar *flx_normalize_name(const gchar *s) {
15     size_t l;
16     g_assert(s);
17
18     l = strlen(s);
19
20     if (!l)
21         return g_strdup(".");
22
23     if (s[l-1] == '.')
24         return g_strdup(s);
25     
26     return g_strdup_printf("%s.", s);
27 }
28
29 gint flx_timeval_compare(const GTimeVal *a, const GTimeVal *b) {
30     g_assert(a);
31     g_assert(b);
32
33     if (a->tv_sec < b->tv_sec)
34         return -1;
35
36     if (a->tv_sec > b->tv_sec)
37         return 1;
38
39     if (a->tv_usec < b->tv_usec)
40         return -1;
41
42     if (a->tv_usec > b->tv_usec)
43         return 1;
44
45     return 0;
46 }
47
48 glong flx_timeval_diff(const GTimeVal *a, const GTimeVal *b) {
49     g_assert(a);
50     g_assert(b);
51     g_assert(flx_timeval_compare(a, b) >= 0);
52
53     return (a->tv_sec - b->tv_sec)*1000000 + a->tv_usec - b->tv_usec;
54 }
55
56
57 gint flx_set_cloexec(gint fd) {
58     gint n;
59
60     g_assert(fd >= 0);
61     
62     if ((n = fcntl(fd, F_GETFD)) < 0)
63         return -1;
64
65     if (n & FD_CLOEXEC)
66         return 0;
67
68     return fcntl(fd, F_SETFD, n|FD_CLOEXEC);
69 }
70
71 gint flx_set_nonblock(gint fd) {
72     gint n;
73
74     g_assert(fd >= 0);
75
76     if ((n = fcntl(fd, F_GETFL)) < 0)
77         return -1;
78
79     if (n & O_NONBLOCK)
80         return 0;
81
82     return fcntl(fd, F_SETFL, n|O_NONBLOCK);
83 }
84
85 gint flx_wait_for_write(gint fd) {
86     fd_set fds;
87     gint r;
88     
89     FD_ZERO(&fds);
90     FD_SET(fd, &fds);
91     
92     if ((r = select(fd+1, NULL, &fds, NULL, NULL)) < 0) {
93         g_message("select() failed: %s", strerror(errno));
94
95         return -1;
96     }
97     
98     g_assert(r > 0);
99
100     return 0;
101 }
102
103 GTimeVal *flx_elapse_time(GTimeVal *tv, guint msec, guint jitter) {
104     g_assert(tv);
105
106     g_get_current_time(tv);
107
108     if (msec)
109         g_time_val_add(tv, msec*1000);
110
111     if (jitter)
112         g_time_val_add(tv, g_random_int_range(0, jitter) * 1000);
113         
114     return tv;
115 }