Kaarsemaker.net

Preview

 1 /*
 2  * Wag: watch a file and wag your tail when it changes.
 3  * Usage: wag /path/to/file /path/to/executable [args for executable]
 4  *
 5  * Every time the mtime of the watched file changes, the executable is executed
 6  * with the arguments as given to wag.
 7  *
 8  * Do not use this if you have inotify available on your system, as inotify is
 9  * the proper way of watching files. I wrote this for a linux 2.4 system where
10  * inotify is not available.
11  *
12  * (c)2009 Dennis Kaarsemaker, dedicated to the public domain.
13  */
14 
15 #include <stdio.h>
 1 /*
 2  * Wag: watch a file and wag your tail when it changes.
 3  * Usage: wag /path/to/file /path/to/executable [args for executable]
 4  *
 5  * Every time the mtime of the watched file changes, the executable is executed
 6  * with the arguments as given to wag.
 7  *
 8  * Do not use this if you have inotify available on your system, as inotify is
 9  * the proper way of watching files. I wrote this for a linux 2.4 system where
10  * inotify is not available.
11  *
12  * (c)2009 Dennis Kaarsemaker, dedicated to the public domain.
13  */
14 
15 #include <stdio.h>
16 #include <stdlib.h>
17 #include <sys/types.h>
18 #include <sys/stat.h>
19 #include <sys/wait.h>
20 #include <unistd.h>
21 
22 void usage(char *prog, int exitcode) {
23     printf("Usage: %s <filename-to-watch> <app-to-execute> [args]\n", prog);
24     puts("The app will be executed whenever the file changes");
25     exit(exitcode);
26 }
27 
28 #define perror_quit(msg) do { perror(msg); exit(1); } while(0)
29 
30 int main(int argc, char **argv) {
31     struct stat buf;
32     char *file;
33     time_t last_change = 0;
34     pid_t child;
35     int status;
36 
37     if(argc < 3)
38         usage(argv[0], 1);
39     file = argv[1];
40     argc -= 2;
41     argv = &(argv[2]);
42 
43     if(access(file, R_OK) || access(argv[0], R_OK|X_OK))
44         usage(argv[0], 2);
45 
46     while(1) {
47         if(stat(file, &buf) == -1)
48             perror_quit("Stat failed");
49 
50         if(buf.st_mtime != last_change) {
51             last_change = buf.st_mtime;
52             child = fork();
53             if(child == -1)
54                 perror_quit("Fork failed");
55             if(child == 0){
56                 execv(argv[0], argv);
57                 perror_quit("Exec failed");
58             }
59             waitpid(child, &status, 0);
60         }
61        sleep(1);
62     }
63 }

Show all