1.作用:
对 文件或目录 进行监控,探测是否发生特定事件。
2.相关api
int inotify_init();
创建监控实例,返回句柄。
int inotify_add_watch(int fd, const char *pathname, uint32_t mask);
添加监控事件,返回监控描述符。
注意:inotify_add_watch对文件有一次性读操作,所以需要有读权限。
int inotify_rm_watch(int fd, uint32_t wd);
删除监控项
3.inotify_event
struct inotify_event { int wd; // 监控描述符 uint32_t mask; //事件 uint32_t cookie; // 相关事件,只用于重命名 uint32_t len; //name域长度 char name[]; //可选的以null结尾的字符串 }
使用read可以获得一个或多个event。
如果read的buf不足一个event,则失败,返回EINVAL.
read buf的最小长度 sizeof(struct inotify_event) + MAX_NAME_LEN + 1
inotify是一个环形队列,所以可以描述事件发生顺序。
若新添加的event各个域与最后一个event相同,那么内核会将其合并,这意味inotify不能描述事件发生频率。
4.实例
#include <stdio.h> #include <unistd.h> #include <sys/inotify.h> #define NAME_MAX 1024 #define BUF_LEN (10 * (sizeof(struct inotify_event) + NAME_MAX + 1)) void displayInotifyEvent(struct inotify_event *i) { printf("name : %s\n", i->name); printf("mask = "); if (i->mask & IN_DELETE_SELF) printf("IN_DELETE_SELF\n"); if (i->mask & IN_OPEN) printf("IN_OPEN\n"); if (i->mask & IN_MODIFY) printf("IN_MODIFY\n"); } int main(int argc, char **argv) { int inotifyFd, i, numRead; char *p, buf[BUF_LEN]; struct inotify_event *event;
if (argc < 2) return 0; inotifyFd = inotify_init(); for (i = 1; i < argc; i++) inotify_add_watch(inotifyFd, argv[i], IN_MODIFY | IN_OPEN); inotify_add_watch(inotifyFd, argv[i], IN_DELETE_SELF | IN_MODIFY | IN_OPEN); for (;;) { numRead = read(inotifyFd, buf, BUF_LEN); if (0 == numRead) break; if (0 > numRead) { printf("failed to read\n"); return -1; } for (p = buf; p < buf + numRead;) { event = (struct inotify_event *)p; displayInotifyEvent(event); p += sizeof(struct inotify_event) + event->len; } } return 0; }