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