summaryrefslogtreecommitdiff
path: root/set_time.c
diff options
context:
space:
mode:
authorJohn Vogel <jvogel4@stny.rr.com>2016-05-15 00:25:04 -0400
committerJohn Vogel <jvogel4@stny.rr.com>2016-05-15 00:25:04 -0400
commit6f412df28ec5a195c80ebd8e091c6b31be88bdcc (patch)
treec9f751774678aae3d2e3d57156755e736b5ed216 /set_time.c
downloadset_time-master.tar.gz
Initial commitHEADmaster
Diffstat (limited to 'set_time.c')
-rw-r--r--set_time.c59
1 files changed, 59 insertions, 0 deletions
diff --git a/set_time.c b/set_time.c
new file mode 100644
index 0000000..9ed5398
--- /dev/null
+++ b/set_time.c
@@ -0,0 +1,59 @@
+/* set_time.c - save/restore system time based on mtime of current program file
+ *
+ * Based on fake-hwclock.c by Xan Manning from
+ * https://github.com/xanmanning/alarm-fake-hwclock/fake-hwclock.c
+ *
+ * Original license:
+ * -----------------------------------------------------------------------------
+ * "THE (COFFEE)WARE LICENSE" (Rev. 1):
+ *
+ * <xan.manning@gmail.com>
+ * wrote this file. As long as you retain this notice you can do whatever you
+ * want with this stuff. If we meet some day, and you think this stuff is
+ * worth it, you can buy me the above drink(s) in return.
+ *
+ * Xan Manning
+ * -----------------------------------------------------------------------------
+ */
+
+#include <stdio.h>
+#include <time.h>
+#include <utime.h>
+#include <sys/stat.h>
+#include <sys/time.h>
+
+int main(int argc, char *argv[])
+{
+ struct stat sb;
+ time_t current_time;
+
+ current_time = time(NULL);
+ if (current_time == (time_t)-1) {
+ fprintf(stderr, "failed to get current time\n");
+ return 1;
+ }
+
+ if (stat(argv[0], &sb) == -1) {
+ fprintf(stderr, "stat failed: %s\n", argv[0]);
+ return 1;
+ }
+
+ if (current_time > sb.st_mtime) {
+ struct utimbuf utb = { current_time, current_time };
+ if (utime(argv[0], &utb) == -1) {
+ fprintf(stderr, "utime failed\n");
+ return 1;
+ }
+ printf("Current time saved\n");
+ }
+ else {
+ struct timespec ts = { current_time + 2, 0 };
+ if (clock_settime(CLOCK_REALTIME, &ts) == -1) {
+ fprintf(stderr, "clock_settime failed\n");
+ return 1;
+ }
+ printf("System time set\n");
+ }
+
+ return 0;
+}