summaryrefslogtreecommitdiffstats
path: root/sync.c
diff options
context:
space:
mode:
Diffstat (limited to 'sync.c')
-rw-r--r--sync.c54
1 files changed, 54 insertions, 0 deletions
diff --git a/sync.c b/sync.c
new file mode 100644
index 0000000..1b6b6bc
--- /dev/null
+++ b/sync.c
@@ -0,0 +1,54 @@
+#include "project.h"
+
+#define SLEEP_MIN 100000
+#define THRESH 1000
+
+void sync_to_second (struct timeval *ret)
+{
+ struct timeval tv1, tv2;
+ ret->tv_usec = 0;
+
+ for (;;) {
+ tv2.tv_sec = 0;
+ gettimeofday (&tv1, NULL);
+ tv2.tv_usec = 1000000 - tv1.tv_usec;
+
+ if (tv1.tv_usec < THRESH) {
+ ret->tv_sec = tv1.tv_sec;
+ return;
+ } else if (tv2.tv_usec < THRESH) {
+ ret->tv_sec = tv1.tv_sec + 1;
+ return;
+ }
+
+ if (tv2.tv_usec > SLEEP_MIN)
+ select (0, NULL, NULL, NULL, &tv2);
+ else
+ usleep (tv2.tv_usec / 2);
+ }
+}
+
+
+
+void sync_to_minute (struct timeval *ret)
+{
+ struct timeval tv1, tv2;
+ ret->tv_usec = 0;
+
+ for (;;) {
+ tv2.tv_sec = 0;
+ gettimeofday (&tv1, NULL);
+ tv2.tv_sec = 60 - (tv1.tv_sec % 60);
+ tv2.tv_usec = 1000;
+
+ printf ("%d seconds left in min\n", (int) tv2.tv_sec);
+
+ if (tv2.tv_sec > 1) {
+ tv2.tv_sec /= 2;
+ select (0, NULL, NULL, NULL, &tv2);
+ } else {
+ sync_to_second (ret);
+ return;
+ }
+ }
+}