inotify介绍
从 Linux 2.6.13 内核开始,Linux 引入了 inotify,可以通过该机制监控文件或目录的一组指定事件,例如打开、关闭、移动/重命名、删除 、创建或更改属性。
inotify提供以下几个API:
inotify_init
#include <sys/inotify.h>
int inotify_init(void);
int inotify_init1(int flags);
创建一个inotify实例并返回一个对应的文件描述符
inotify_add_watch
#include <sys/inotify.h>
int inotify_add_watch(int fd, const char *pathname, uint32_t mask);
操作inotify实例相关联的“watch list”(创建或者修改已有的)
当受监视的文件和目录发生事件时,可以使用 read从 inotify 文件描述符中读取这些事件信息
inotify_rm_watch
#include <sys/inotify.h>
int inotify_rm_watch(int fd, int wd);
从inotify监控列表中删除项目
当与 inotify 实例相关的所有文件描述符都已关闭(使用 close)时,内核会释放对应的底层对象及其资源以供重用; 所有关联的监控都会被自动释放
至此,我们可以知道一个监控程序需要执行的大概步骤:
- 使用inotify_init或者inotify_init1获取一个文件描述符
- 使用inotify_add_watch添加一个或者多个需要监控的文件或目录
- 等待事件发生
- 处理事件并继续等待下一次事件
- 当不再需要监控时,关闭文件描述符、清理并退出。
使用
从一个inotify文件描述符中读取事件
为了知道发生的事件,可以通过read对应的inotify文件描述符来获取相关信息。如果该文件描述符为blocking,那么read会一直阻塞知道事件发生。
我们从inotify文件描述符中获取到如下的事件结构体:
struct inotify_event
{
int wd; /* Watch descriptor. */
uint32_t mask; /* Mask describing event. */
uint32_t cookie; /* Unique cookie associating related
events (for rename(2)) */
uint32_t len; /* Size of name field. */
char name[]; /* Optional null-terminated name. */
};
wd:标识发生事件的监控对象,他是之前通过inotify_add_watch返回的一个监控描述符
mask:里面有对应发生事件的标志位
cookie:是连接相关事件的唯一性整数。 目前仅用于重命名事件,用于将 IN_MOVED_FROM 事件与相应的 IN_MOVED_TO 事件关联起来。 对于所有其他事件类型,cookie 设置为 0。
name:只在监控目录时返回该目录下的文件名(以null(‘\0’)结尾的字符串,为了对齐可能会有多个’\0’。
len: name中所有的字符个数,包括所有的null(‘\0’)字符。所以,一个完整的inotify_event的大小应该为sizeof(struct inotify_event)+len。
inotify事件
inotify_add_watch接口中mask参数以及inotify_event中的mask参数都是bit mask定义的inotify事件.
下面这些事件可以同时作为inotify_add_watch的mask参数以及inotify_event中的mask返回:
IN_ACCESS (+)
File was accessed (e.g., read(2), execve(2)).
IN_ATTRIB (*)
Metadata changed—for example, permissions (e.g., chmod(2)), timestamps (e.g., utimensat(2)), extended attributes (setxattr(2)), link count (since Linux 2.6.25; e.g., for the target of link(2) and for unlink(2)), and user/group ID (e.g., chown(2)).
IN_CLOSE_WRITE (+)
File opened for writing was closed.
IN_CLOSE_NOWRITE (*)
File or directory not opened for writing was closed.
IN_CREATE (+)
File/directory created in watched directory (e.g., open(2) O_CREAT, mkdir(2), link(2), symlink(2), bind(2) on a UNIX domain socket).
IN_DELETE (

最低0.47元/天 解锁文章
2266

被折叠的 条评论
为什么被折叠?



