-
Notifications
You must be signed in to change notification settings - Fork 0
/
watchtower.c
76 lines (59 loc) · 1.82 KB
/
watchtower.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
#include <stdio.h>
#include <sys/inotify.h>
#include <limits.h>
#include <time.h>
#define BUF_LEN (10 * (sizeof(struct inotify_event) + NAME_MAX + 1))
time_t lastRun = 0;
static void handleModification(struct inotify_event *i, char *script)
{
if (i->mask & IN_MODIFY) {
time_t currentTime = time(NULL);
if (currentTime - lastRun > 1) {
printf("[%s]Ran script %s", ctime(¤tTime), script);
printf("\n");
system(script);
lastRun = currentTime;
}
}
}
int main(int argc, char *argv[])
{
int inotifyFd, wd, j;
char buf[BUF_LEN] __attribute__ ((aligned(8)));
ssize_t numRead;
char *p;
struct inotify_event *event;
if (argc < 3 || strcmp(argv[1], "--help") == 0) {
printf("%s: run a script when files changes \n", argv[0]);
printf("%s script pathname...\n", argv[0]);
return -1;
}
inotifyFd = inotify_init();
if (inotifyFd == -1) {
printf("inotify_init");
return -1;
}
for (j = 2; j < argc; j++) {
wd = inotify_add_watch(inotifyFd, argv[j], IN_MODIFY); // Watch each file from command line
if (wd == -1) {
printf("inotify_add_watch");
return -1;
}
printf("Watching %s\n", argv[j]);
}
for (;;) {
numRead = read(inotifyFd, buf, BUF_LEN);
if (numRead == 0) {
printf("read() from inotify fd returned 0!");
return -1;
}
if (numRead == -1)
return -1;
for (p = buf; p < buf + numRead; ) {
event = (struct inotify_event *) p;
handleModification(event, argv[1]);
p += sizeof(struct inotify_event) + event->len;
}
}
return 0;
}