]> git.meshlink.io Git - catta/blobdiff - util.c
add client part of probing
[catta] / util.c
diff --git a/util.c b/util.c
index 62574ba524d83920bf9b8f448ef3f90deeae3987..3edaa8878398166b13e36bfc3efdba6a404cabc5 100644 (file)
--- a/util.c
+++ b/util.c
@@ -1,5 +1,7 @@
 #include <string.h>
 #include <unistd.h>
+#include <fcntl.h>
+#include <errno.h>
 
 #include "util.h"
 
@@ -46,7 +48,80 @@ gint flx_timeval_compare(const GTimeVal *a, const GTimeVal *b) {
 glong flx_timeval_diff(const GTimeVal *a, const GTimeVal *b) {
     g_assert(a);
     g_assert(b);
-    g_assert(flx_timeval_compare(a, b) >= 0);
 
-    return (a->tv_sec - b->tv_sec)*1000000 + a->tv_usec - b->tv_usec;
+    if (flx_timeval_compare(a, b) < 0)
+        return flx_timeval_diff(b, a);
+
+    return ((glong) a->tv_sec - b->tv_sec)*1000000 + a->tv_usec - b->tv_usec;
+}
+
+
+gint flx_set_cloexec(gint fd) {
+    gint n;
+
+    g_assert(fd >= 0);
+    
+    if ((n = fcntl(fd, F_GETFD)) < 0)
+        return -1;
+
+    if (n & FD_CLOEXEC)
+        return 0;
+
+    return fcntl(fd, F_SETFD, n|FD_CLOEXEC);
+}
+
+gint flx_set_nonblock(gint fd) {
+    gint n;
+
+    g_assert(fd >= 0);
+
+    if ((n = fcntl(fd, F_GETFL)) < 0)
+        return -1;
+
+    if (n & O_NONBLOCK)
+        return 0;
+
+    return fcntl(fd, F_SETFL, n|O_NONBLOCK);
+}
+
+gint flx_wait_for_write(gint fd) {
+    fd_set fds;
+    gint r;
+    
+    FD_ZERO(&fds);
+    FD_SET(fd, &fds);
+    
+    if ((r = select(fd+1, NULL, &fds, NULL, NULL)) < 0) {
+        g_message("select() failed: %s", strerror(errno));
+
+        return -1;
+    }
+    
+    g_assert(r > 0);
+
+    return 0;
+}
+
+GTimeVal *flx_elapse_time(GTimeVal *tv, guint msec, guint jitter) {
+    g_assert(tv);
+
+    g_get_current_time(tv);
+
+    if (msec)
+        g_time_val_add(tv, msec*1000);
+
+    if (jitter)
+        g_time_val_add(tv, g_random_int_range(0, jitter) * 1000);
+        
+    return tv;
+}
+
+gint flx_age(const GTimeVal *a) {
+    GTimeVal now;
+    
+    g_assert(a);
+
+    g_get_current_time(&now);
+
+    return flx_timeval_diff(&now, a);
 }