libuv-example-onchang

libuv onchang example
不同OS,低層採用不同方式來處理inotify
inotify on Linux, FSEvents on Darwin, kqueue on BSDs, ReadDirectoryChangesW on Windows, event ports on Solaris, unsupported on Cygwin


更新記錄

item note
20160516 第一版

目錄


libuv onchang example

範例說明

  • 參考來源
  • All modern operating systems provide APIs to put watches on individual files or directories and be informed when the files are modified.
  • The file change notification is started using uv_fs_event_init():
  • int uv_fs_event_start(handle,cb,path,flags)
    • path: 可以為檔案或目錄
    • flags: 目前只有UV_FS_EVENT_RECURSIVE,當目錄或檔案有變更即通知
  • example code

範例內容

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
void run_command(uv_fs_event_t *handle, const char *filename, int events, int status) {
char path[1024];
size_t size = 1023;
// Does not handle error if path is longer than 1023.
uv_fs_event_getpath(handle, path, &size);
path[size] = '\0';

fprintf(stderr, "Change detected in %s: ", path);
if (events & UV_RENAME)
fprintf(stderr, "renamed");
if (events & UV_CHANGE)
fprintf(stderr, "changed");

fprintf(stderr, " %s\n", filename ? filename : "");
system(command);
}

int main(int argc, char **argv) {
..

loop = uv_default_loop();
command = argv[1];

..
uv_fs_event_init(loop, fs_event_req);
// The recursive flag watches subdirectories too.
uv_fs_event_start(fs_event_req, run_command, argv[argc], UV_FS_EVENT_RECURSIVE);
..
return uv_run(loop, UV_RUN_DEFAULT);
}

範例測試

  • 設定command:ls ,檢查Makefiel是否有變更
  • 試著修改Makefile,產生3次的rename及1次的onchang
1
2
3
4
5
6
7
8
9
10
[ubuntu](master-de06992)0h9m root@e8b0cd737680:[t05_onchange]$ ./t05-main-ubuntu ls Makefile 
Adding watch on Makefile
Change detected in Makefile: renamed Makefile
Makefile main.c main.o t05-main-ubuntu
Change detected in Makefile: changed Makefile
Makefile main.c main.o t05-main-ubuntu
Change detected in Makefile: renamed Makefile
Makefile main.c main.o t05-main-ubuntu
Change detected in Makefile: renamed Makefile
Makefile main.c main.o t05-main-ubuntu

參考來源