-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrtcd.c
79 lines (68 loc) · 1.76 KB
/
rtcd.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <err.h>
#include <stdbool.h>
#include <fcntl.h>
#include <unistd.h>
#include "rtclib.h"
#define MAX_DELTA 2
#define DEF_INT 5
#define DEF_RTC_PATH "/dev/rtc0"
static void print_help();
static inline time_t ttabs(time_t v) {
return v >= 0 ? v : -v;
}
int main(int argc, const char ** argv) {
const char * dev = DEF_RTC_PATH;
int interval = DEF_INT;
// parse args
for (int argi = 1; argi < argc; ++argi) {
if (strcmp(argv[argi], "-i") == 0) {
interval = atoi(argv[++argi]);
if (interval < 0) {
fputs("Interval must be a positive number.\n", stderr);
return 1;
}
continue;
} else if (strcmp(argv[argi], "-d") == 0) {
dev = argv[++argi];
continue;
} else if (strcmp(argv[argi], "-h") == 0) {
print_help();
return 0;
} else {
print_help();
return 1;
}
}
printf("Monitoring '%s' with interval of %d sec\n", dev, interval);
int fd = open(dev, O_RDONLY);
if (fd < 0) {
err(1, "Error opening RTC device");
}
for(;;usleep(interval * 1000 * 1000)) {
struct tm rtc_tm;
if (read_rtc_time(fd, &rtc_tm) < 0) {
warn("Error reading RTC time");
continue;
}
time_t rtctime = timegm(&rtc_tm);
time_t systime = read_sys_time();
time_t time_delta = rtctime - systime;
if (ttabs(time_delta) > MAX_DELTA) {
printf("System time is %s from RTC time by %ld seconds. Synching.\n",
time_delta > 0 ? "behind" : "ahead",
ttabs(time_delta));
if (set_system_time_from_utc(rtctime) < 0) {
warn("Error setting system time");
}
}
}
}
static void print_help() {
puts("Usage: rtcd [OPTIONS])");
puts("Options are:");
printf(" -i Set the refresh interval in second (default %d)\n", DEF_INT);
printf(" -d RTC device path (default %s)\n", DEF_RTC_PATH);
}