xref: /netbsd-src/external/mit/libuv/dist/docs/code/onchange/main.c (revision 0e552da7216834a96e91ad098e59272b41087480)
1*0e552da7Schristos #include <stdio.h>
2*0e552da7Schristos #include <stdlib.h>
3*0e552da7Schristos 
4*0e552da7Schristos #include <uv.h>
5*0e552da7Schristos 
6*0e552da7Schristos uv_loop_t *loop;
7*0e552da7Schristos const char *command;
8*0e552da7Schristos 
run_command(uv_fs_event_t * handle,const char * filename,int events,int status)9*0e552da7Schristos void run_command(uv_fs_event_t *handle, const char *filename, int events, int status) {
10*0e552da7Schristos     char path[1024];
11*0e552da7Schristos     size_t size = 1023;
12*0e552da7Schristos     // Does not handle error if path is longer than 1023.
13*0e552da7Schristos     uv_fs_event_getpath(handle, path, &size);
14*0e552da7Schristos     path[size] = '\0';
15*0e552da7Schristos 
16*0e552da7Schristos     fprintf(stderr, "Change detected in %s: ", path);
17*0e552da7Schristos     if (events & UV_RENAME)
18*0e552da7Schristos         fprintf(stderr, "renamed");
19*0e552da7Schristos     if (events & UV_CHANGE)
20*0e552da7Schristos         fprintf(stderr, "changed");
21*0e552da7Schristos 
22*0e552da7Schristos     fprintf(stderr, " %s\n", filename ? filename : "");
23*0e552da7Schristos     system(command);
24*0e552da7Schristos }
25*0e552da7Schristos 
main(int argc,char ** argv)26*0e552da7Schristos int main(int argc, char **argv) {
27*0e552da7Schristos     if (argc <= 2) {
28*0e552da7Schristos         fprintf(stderr, "Usage: %s <command> <file1> [file2 ...]\n", argv[0]);
29*0e552da7Schristos         return 1;
30*0e552da7Schristos     }
31*0e552da7Schristos 
32*0e552da7Schristos     loop = uv_default_loop();
33*0e552da7Schristos     command = argv[1];
34*0e552da7Schristos 
35*0e552da7Schristos     while (argc-- > 2) {
36*0e552da7Schristos         fprintf(stderr, "Adding watch on %s\n", argv[argc]);
37*0e552da7Schristos         uv_fs_event_t *fs_event_req = malloc(sizeof(uv_fs_event_t));
38*0e552da7Schristos         uv_fs_event_init(loop, fs_event_req);
39*0e552da7Schristos         // The recursive flag watches subdirectories too.
40*0e552da7Schristos         uv_fs_event_start(fs_event_req, run_command, argv[argc], UV_FS_EVENT_RECURSIVE);
41*0e552da7Schristos     }
42*0e552da7Schristos 
43*0e552da7Schristos     return uv_run(loop, UV_RUN_DEFAULT);
44*0e552da7Schristos }
45