inotify例程
#include #include #include char * monitored_files[] = {...
扫描右侧二维码阅读全文
11
2008/04

inotify例程

#include #include #include char * monitored_files[] = { "./tmp_file", "./tmp_dir", "/mnt/sda3/windows_file" }; struct wd_name { int wd; char * name; }; #define WD_NUM 3 struct wd_name wd_array[WD_NUM]; //用于存储文件路径名和watch描述符 //inotify机制事件对应说明数组 char * event_array[] = { "File was accessed", "File was modified", "File attributes were changed", "writtable file closed", "Unwrittable file closed", "File was opened", "File was moved from X", "File was moved to Y", "Subfile was created", "Subfile was deleted", "Self was deleted", "Self was moved", "", "Backing fs was unmounted", "Event queued overflowed", "File was ignored" }; #define EVENT_NUM 16 #define MAX_BUF_SIZE 1024 int main(void) { int fd; int wd; char buffer[1024]; char * offset = NULL; struct inotify_event * event; int len, tmp_len; char strbuf[16]; int i = 0; fd = inotify_init(); if (fd < 0) { printf("Fail to initialize inotify.\n"); exit(-1); } for (i=0; i< WD_NUM; i++) { wd_array.name = monitored_files; //存入文件路径名 //给路径wd_array.name添加一个watch,监视所有事件,wd为返回的watch描述符 wd = inotify_add_watch(fd, wd_array.name, IN_ALL_EVENTS); if (wd < 0) { printf("Can't add watch for %s.\n", wd_array.name); exit(-1); } wd_array.wd = wd; } while(len = read(fd, buffer, MAX_BUF_SIZE)) { //读取多个事件 offset = buffer; printf("Some event happens, len = %d.\n", len); //打印实际读取的长度 event = (struct inotify_event *)buffer; //得到事件 while (((char *)event - buffer) < len) { if (event-> mask & IN_ISDIR) { //目录 memcpy(strbuf, "Direcotory", 11); //“Direcotory”字符串长度为11 } else { memcpy(strbuf, "File", 5); //“File”字符串长度为5,包括后面加一个空格 } printf("Object type: %s\n", strbuf); for (i=0; i< WD_NUM; i++) { if (event-> wd != wd_array.wd) continue; printf("Object name: %s\n", wd_array.name); //打印文件路径名 break; } printf("Event mask: %08X\n", event-> mask); //打印事件掩码 for (i=0; i< EVENT_NUM ; i++) { if (event_array[0] == '\0') //空字符串行,说明事件对应说明不存在 continue; //将事件掩码的位匹配数组成员,如:00000020,即100000,对应i为5 if (event-> mask & (1 << i)) { printf("Event: %s\n", event_array);   //打印事件对应的说明字符串 } } tmp_len = sizeof(struct inotify_event) + event-> len; event = (struct inotify_event *)(offset + tmp_len); //得到下一个事件 offset += tmp_len; } } }

Last modification:November 26th, 2018 at 04:16 pm
If you think my article is useful to you, please feel free to appreciate

Leave a Comment