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
|
/* 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;
}
|