i007.cc

i007.cc

优先队列-降维打击

Inotify机制

Inotify机制

原创 2017年01月04日 14:14:13

描述

Inotify API用于检测文件系统变化的机制。Inotify可用于检测单个文件,也可以检测整个目录。当检测的对象是一个目录的时候,目录本身和目录里的内容都会成为检测的对象。

此种机制的出现的目的是当内核空间发生某种事件之后,可以立即通知到用户空间。方便用户做出具体的操作。

Inotify API

  • inotify_init(void)

用于创建一个inotify的实例,然后返回inotify事件队列的文件描述符。 同样内核也提供了inotify_init1(int flags)接口函数,当flag等于0的时候,该函数等价于inotify_init(void)函数。

  • inotify_add_watch(int fd, const char* pathname, uint32_t  mask)

该函数用于添加“watch list”,也就是检测列表。 可以是一个新的watch,也可以是一个已经存在的watch。其中fd就是inotify_init的返回值,pathname是要检测目录或者文件的路径,mask就是要检测的事件类型。该函数成功返回的是一个unique的watch描述符。

  • inotify_rm_watch(int fd, int wd)

用于从watch list种移除检测的对象。

 

数据结构

内核使用struct inotify_event代表一个文件事件。当检测的文件对象发生变化时,使用read系统调用就会返回一个或者多个inotify_event的文件事件对象。

[csharp] view plain copy

  1. struct inotify_event {
  2.    int      wd;       /* Watch descriptor */
  3.    uint32_t mask;     /* Mask of events */
  4.    uint32_t cookie;   /* Unique cookie associating related
  5.                          events (for rename(2)) */
  6.    uint32_t len;      /* Size of name field */
  7.    char     name[];   /* Optional null-terminated name */
  8. };

.wd:        就是检测的对象的watch descriptor

.mask:    检测事件的mask

.cookie:  和rename事件相关。

.len:        name字段的长度。

.name:    检测对象的name。

可以看到name字段的长度是0,也就是变长的。因为检测的对象的name不定,使用变长可以方便记录检测对象的name。

 

有关检测的事件类型分为好几种,如下:

[cpp] view plain copy

  1. IN_ACCESS         File was accessed (read) (*).
  2. IN_ATTRIB         Metadata  changed,  e.g.,  permissions, timestamps, extended
  3.                  attributes, link count (since Linux 2.6.25), UID, GID,  etc.(*).
  4. IN_CLOSE_WRITE    File opened for writing was closed (*).
  5. IN_CLOSE_NOWRITE  File not opened for writing was closed (*).
  6. IN_CREATE         File/directory created in watched directory (*).
  7. IN_DELETE         File/directory deleted from watched directory (*).
  8. IN_DELETE_SELF    Watched file/directory was itself deleted.
  9. IN_MODIFY         File was modified (*).
  10. IN_MOVE_SELF      Watched file/directory was itself moved.
  11. IN_MOVED_FROM     File moved out of watched directory (*).
  12. IN_MOVED_TO       File moved into watched directory (*).
  13. IN_OPEN           File was opened (*).

注释写的很清楚,不再一一解释了。

 

实例分析

[cpp] view plain copy

  1. #include <sys/inotify.h>
  2. #include <unistd.h>
  3. #include <string.h>
  4. #include <stdio.h>
  5. /*
  6. struct inotify_event {
  7.    int      wd;       // Watch descriptor 
  8.    uint32_t mask;     // Mask of events 
  9.    uint32_t cookie;   // Unique cookie associating related  events (for rename(2))
  10.    uint32_t len;      // Size of name field 
  11.    char     name[];   // Optional null-terminated name 
  12. };
  13. */
  14. int watch_inotify_events(int fd)
  15. {
  16.     char event_buf[512];
  17.     int ret;
  18.     int event_pos = 0;
  19.     int event_size = 0;
  20.     struct inotify_event *event;
  21.     /*读事件是否发生,没有发生就会阻塞*/
  22.     ret = read(fd, event_buf, sizeof(event_buf));
  23.     /*如果read的返回值,小于inotify_event大小出现错误*/
  24.     if(ret < (int)sizeof(struct inotify_event))
  25.     {
  26.         printf(“counld not get event!\n”);
  27.         return -1;
  28.     }
  29.     /*因为read的返回值存在一个或者多个inotify_event对象,需要一个一个取出来处理*/
  30.     while( ret >= (int)sizeof(struct inotify_event) )
  31.     {
  32.         event = (struct inotify_event*)(event_buf + event_pos);
  33.         if(event->len)
  34.         {
  35.             if(event->mask & IN_CREATE)
  36.             {
  37.                 printf(“create file: %s\n”,event->name);
  38.             }
  39.             else
  40.             {
  41.                 printf(“delete file: %s\n”,event->name);
  42.             }
  43.         }
  44.         /*event_size就是一个事件的真正大小*/
  45.         event_size = sizeof(struct inotify_event) + event->len;
  46.         ret -= event_size;
  47.         event_pos += event_size;
  48.     }
  49.     return 0;
  50. }
  51. int main(int argc, char** argv)
  52. {
  53.     int InotifyFd;
  54.     int ret;
  55.     if (argc != 2)
  56.     {
  57.         printf(“Usage: %s <dir>\n”, argv[0]);
  58.         return -1;
  59.     }
  60.     /*inotify初始化*/
  61.     InotifyFd = inotify_init();
  62.     if( InotifyFd == -1)
  63.     {
  64.         printf(“inotify_init error!\n”);
  65.         return -1;
  66.     }
  67.     /*添加watch对象*/
  68.     ret = inotify_add_watch(InotifyFd, argv[1], IN_CREATE |  IN_DELETE);
  69.     /*处理事件*/
  70.     watch_inotify_events(InotifyFd);
  71.     /*删除inotify的watch对象*/
  72.     if ( inotify_rm_watch(InotifyFd, ret) == -1)
  73.     {
  74.         printf(“notify_rm_watch error!\n”);
  75.         return -1;
  76.     }
  77.     /*关闭inotify描述符*/
  78.     close(InotifyFd);
  79.     return 0;
  80. }
1.  编译代码
[cpp] view plain copy

  1. gcc inotify.c -o inotify

2. 在tmp目录下创建test目录

[cpp] view plain copy

  1. mkdir /tmp/test

3.  检测/tmp/test目录,使用inotify机制

[cpp] view plain copy

  1. ./inotify /tmp/test &

4.  在/tmp/test下创建1.txt文件

[cpp] view plain copy

  1. test$ touch /tmp/test/1.txt
  2. create file: 1.txt
版权声明:本文为博主原创文章,未经博主允许不得转载。

One thought on “Inotify机制

  • 匿名

    inotify 编辑
    Inotify 是一个 Linux特性,它监控文件系统操作,比如读取、写入和创建。Inotify 反应灵敏,用法非常简单,并且比 cron 任务的繁忙轮询高效得多。学习如何将 inotify 集成到您的应用程序中,并发现一组可用来进一步自动化系统治理的命令行工具。
    外文名 inotify 含 义 一个 Linux特性 用 途 监控文件系统操作 性 质 命令行工具
    目录
    1 产生背景
    2 详细介绍
    产生背景编辑
    系统治理就像日常生活一样。就像刷牙和吃蔬菜一样,日常的维护能保持机器的良好状态。您必须定期清空废物,比如临时文件或无用的日志文件,以及花时间填写表单、回复电话、更新和监控进程等。幸好自动化 shell 脚本、使用 Nagios 等工具进行监控、通过常见的 cron 进行任务调度可以减轻这个负担。
    但稀奇的是,这些工具没有一个具有响应性。当然,您可以安排一个频繁运行的 cron 任务来监控条件,但这样繁忙的轮询 — 消耗大量资源并且具有不确定性 — 并不是很理想。例如,假如您必须监控输入数据的几个 Transfer Protocol(FTP)收存箱,您可能要通过 find 命令扫描每个目标目录,列举新的内容。然而,尽管这个操作看起来并没有什么害处,但每个调用都产生一个新的 shell 和 find 命令,这需要许多系统调用来打开目录,然后扫描目录,等等。这会造成过于频繁的或大量的轮询任务(更糟糕的是,繁忙的轮询并不总是很好。想象一下一个文件系统浏览器,比如 Mac OS X 的 Finder,轮询更新时需要的大量资源及其复杂性)。
    那么,管理员应该怎么办呢?令人兴奋的是,您可以再次求助于可以信赖的计算机。
    详细介绍编辑
    Inotify 是一个 Linux 内核特性,它监控文件系统,并且及时向专门的应用程序发出相关的事件警告,比如删除、读、写和卸载操作等。您还可以跟踪活动的源头和目标等细节。
    使用 inotify 很简单:创建一个文件描述符,附加一个或多个监视器(一个监视器 是一个路径和一组事件),然后使用 read 方法从描述符获取事件。read 并不会用光整个周期,它在事件发生之前是被阻塞的。
    更好的是,因为 inotify 通过传统的文件描述符工作,您可以利用传统的 select 系统调用来被动地监控监视器和许多其他输入源。两种方法 — 阻塞文件描述符和使用 select— 都避免了繁忙轮询。
    现在,深入了解 inotify,写一些 C 代码,然后看看一组命令行工具,可以构建并使用它们将命令和脚本附加到文件系统事件。Inotify 不会在中途失去控制,但它可以运行 cat 和 wget,并且在必要时严格执行。
    要使用 inotify,必须具备一台带有 2.6.13 或更新内核的 Linux 机器(以前的 Linux 内核版本使用更低级的文件监控器 dnotify)。如果不知道内核的版本,请转到 shell,输入 uname -a:
    % uname -a
    Linux ubuntu-desktop 2.6.24-19-generic #1 SMP … i686 GNU/Linux
    如果列出的内核版本不低于 2.6.13,系统就支持 inotify。还可以检查机器的 /usr/include/sys/inotify.h 文件。如果它存在,表明内核支持 inotify。
    注意:FreeBSD 和 Mac OS X 提供一个类似于 inotify 的 kqueue。在 FreeBSD 机器上输入 man 2 kqueue 获取更多信息。
    本文基于 Ubuntu Desktop version 8.04.1(即 Hardy),它运行在 Mac OS X version 10.5 Leopard 的 Parallels Desktop version 3.0。

发表回复