文件系统监控——inotify

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)时,内核会释放对应的底层对象及其资源以供重用; 所有关联的监控都会被自动释放
至此,我们可以知道一个监控程序需要执行的大概步骤:

  1. 使用inotify_init或者inotify_init1获取一个文件描述符
  2. 使用inotify_add_watch添加一个或者多个需要监控的文件或目录
  3. 等待事件发生
  4. 处理事件并继续等待下一次事件
  5. 当不再需要监控时,关闭文件描述符、清理并退出。

使用

从一个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 (
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值