您当前的位置:首页 > 计算机 > 系统应用 > Linux

文件系统监控——inotify

时间:08-01来源:作者:点击数:

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 (+)
File/directory deleted from watched directory.

IN_DELETE_SELF
Watched  file/directory  was  itself deleted.  (This event also occurs if an object is moved to another filesystem, since mv(1) in effect copies the file to the other filesystem and then deletes it from the original filesystem.)  In addition, an IN_IGNORED event will subsequently be generated for the  watch  descriptor.

IN_MODIFY (+)
File was modified (e.g., write(2), truncate(2)).

IN_MOVE_SELF
Watched file/directory was itself moved.

IN_MOVED_FROM (+)
Generated for the directory containing the old filename when a file is renamed.

IN_MOVED_TO (+)
Generated for the directory containing the new filename when a file is renamed.

IN_OPEN (*)
File or directory was opened.

inotify监控是基于inode的,所以当监控文件发生事件,其他链接到该文件的文件也会产生事件,即使他们可能在不同的目录下面。

当监控一个目录时:

  • 上面以*标记的事件可能同时在监控的目录自身和处于目录中的对象上
  • 上面一+标记的事件只会发生在处于目录中的对象上而不是目录自身

当监控目录时,如果目录内的文件是以链接这类方式链接到目录外的文件,那么inotify不会为该文件产生对应的事件

当被监控目录中的文件产生事件时,inotify_event中的name会包含目录名。

IN_ALL_EVENTS事件可以指代上面所有的事件,你可以在调用inotify_add_watch时使用。

还有两个常用的事件:

IN_MOVE
Equates to IN_MOVED_FROM | IN_MOVED_TO.

IN_CLOSE
Equates to IN_CLOSE_WRITE | IN_CLOSE_NOWRITE.

下面的几个特殊的标识可以在inotify_add_watch中使用:

IN_DONT_FOLLOW (since Linux 2.6.15)
Don't dereference pathname if it is a symbolic link.

IN_EXCL_UNLINK (since Linux 2.6.36)
By default, when watching events on the children of a directory, events are generated for children even after they have been unlinked  from  the  directory.
This  can  result  in large numbers of uninteresting events for some applications (e.g., if watching /tmp, in which many applications create temporary files whose names are immediately unlinked).  Specifying IN_EXCL_UNLINK changes the default behavior, so that events are not generated  for  children  after  they have been unlinked from the watched directory.

IN_MASK_ADD
If  a watch instance already exists for the filesystem object corresponding to pathname, add (OR) the events in mask to the watch mask (instead of replacing the mask); the error EINVAL results if IN_MASK_CREATE is also specified.

IN_ONESHOT
Monitor the filesystem object corresponding to pathname for one event, then remove from watch list.

IN_ONLYDIR (since Linux 2.6.15)
Watch pathname only if it is a directory; the error ENOTDIR results if pathname is not a directory.  Using this flag provides an application  with  a  race-free way of ensuring that the monitored object is a directory.

IN_MASK_CREATE (since Linux 4.18)
Watch pathname only if it does not already have a watch associated with it; the error EEXIST results if pathname is already being watched.

Using  this flag provides an application with a way of ensuring that new watches do not modify existing ones.  This is useful because multiple paths may refer to the same inode, and multiple calls to inotify_add_watch(2) without this flag may clobber existing watch masks.

下面的几个标识可能会在inotify_event中:

IN_IGNORED
Watch was removed explicitly (inotify_rm_watch(2)) or automatically (file was deleted, or filesystem was unmounted).  See also BUGS.

IN_ISDIR
Subject of this event is a directory.

IN_Q_OVERFLOW
Event queue overflowed (wd is -1 for this event).

IN_UNMOUNT
Filesystem containing watched object was unmounted.  In addition, an IN_IGNORED event will subsequently be generated for the watch descriptor.

事件例子

Suppose an application is watching the directory dir and the file dir/myfile for all events. The examples below show some events that will be generated for these two objects.

fd = open("dir/myfile", O_RDWR);
Generates IN_OPEN events for both dir and dir/myfile.

read(fd, buf, count);
Generates IN_ACCESS events for both dir and dir/myfile.

write(fd, buf, count);
Generates IN_MODIFY events for both dir and dir/myfile.

fchmod(fd, mode);
Generates IN_ATTRIB events for both dir and dir/myfile.

close(fd);
Generates IN_CLOSE_WRITE events for both dir and dir/myfile.

Suppose an application is watching the directories dir1 and dir2, and the file dir1/myfile. The following examples show some events that may be generated.

link("dir1/myfile", "dir2/new");
Generates an IN_ATTRIB event for myfile and an IN_CREATE event for dir2.

rename("dir1/myfile", "dir2/myfile");
Generates  an  IN_MOVED_FROM  event for dir1, an IN_MOVED_TO event for dir2, and an IN_MOVE_SELF event for myfile.  The IN_MOVED_FROM and IN_MOVED_TO events  will have the same cookie value.

Suppose that dir1/xx and dir2/yy are (the only) links to the same file, and an application is watching dir1, dir2, dir1/xx, and dir2/yy. Executing the following calls in the order given below will generate the following events:

unlink("dir2/yy");
Generates an IN_ATTRIB event for xx (because its link count changes) and an IN_DELETE event for dir2.

unlink("dir1/xx");
Generates IN_ATTRIB, IN_DELETE_SELF, and IN_IGNORED events for xx, and an IN_DELETE event for dir1.

Suppose an application is watching the directory dir and (the empty) directory dir/subdir. The following examples show some events that may be generated.

mkdir("dir/new", mode);
Generates an IN_CREATE | IN_ISDIR event for dir.

rmdir("dir/subdir");
Generates IN_DELETE_SELF and IN_IGNORED events for subdir, and an IN_DELETE | IN_ISDIR event for dir.

系统设置

The following interfaces can be used to limit the amount of kernel memory consumed by inotify:

/proc/sys/fs/inotify/max_queued_events

The value in this file is used when an application calls inotify_init() to set an upper limit on the number of events that can be queued to the corresponding inotify instance. Events in excess of this limit are dropped, but an IN_Q_OVERFLOW event is always generated.

/proc/sys/fs/inotify/max_user_instances

This specifies an upper limit on the number of inotify instances that can be created per real user ID.

/proc/sys/fs/inotify/max_user_watches

This specifies an upper limit on the number of watches that can be created per real user ID.

代码
// https://man7.org/linux/man-pages/man7/inotify.7.html
#include <errno.h>
#include <poll.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/inotify.h>
#include <unistd.h>

/* Read all available inotify events from the file descriptor 'fd'.
   wd is the table of watch descriptors for the directories in argv.
   argc is the length of wd and argv.
   argv is the list of watched directories.
   Entry 0 of wd and argv is unused. */
static void handle_events(int fd, int *wd, int argc, char *argv[])
{
    /* Some systems cannot read integer variables if they are not
       properly aligned. On other systems, incorrect alignment may
       decrease performance. Hence, the buffer used for reading from
       the inotify file descriptor should have the same alignment as
       struct inotify_event. */
    char buf[4096] __attribute__((aligned(__alignof__(struct inotify_event))));
    const struct inotify_event *event;
    ssize_t len;
    /* Loop while events can be read from inotify file descriptor. */
    for (;;) {
        /* Read some events. */
        len = read(fd, buf, sizeof(buf));
        if (len == -1 && errno != EAGAIN) {
            perror("read");
            exit(EXIT_FAILURE);
        }
        /* If the nonblocking read() found no events to read, then
           it returns -1 with errno set to EAGAIN. In that case,
           we exit the loop. */
        if (len <= 0) break;
        /* Loop over all events in the buffer. */
        for (char *ptr = buf; ptr < buf + len;
             ptr += sizeof(struct inotify_event) + event->len) {
            event = (const struct inotify_event *)ptr;
            /* Print event type. */
            if (event->mask & IN_OPEN) printf("IN_OPEN: ");
            if (event->mask & IN_CLOSE_NOWRITE) printf("IN_CLOSE_NOWRITE: ");
            if (event->mask & IN_CLOSE_WRITE) printf("IN_CLOSE_WRITE: ");
            /* Print the name of the watched directory. */
            for (size_t i = 1; i < argc; ++i) {
                if (wd[i] == event->wd) {
                    printf("%s/", argv[i]);
                    break;
                }
            }
            /* Print the name of the file. */
            if (event->len) printf("%s", event->name);
            /* Print type of filesystem object. */
            if (event->mask & IN_ISDIR)
                printf(" [directory]\n");
            else
                printf(" [file]\n");
        }
    }
}
int main(int argc, char *argv[])
{
    char buf;
    int fd, i, poll_num;
    int *wd;
    nfds_t nfds;
    struct pollfd fds[2];
    if (argc < 2) {
        printf("Usage: %s PATH [PATH ...]\n", argv[0]);
        exit(EXIT_FAILURE);
    }
    printf("Press ENTER key to terminate.\n");
    /* Create the file descriptor for accessing the inotify API. */
    fd = inotify_init1(IN_NONBLOCK);
    if (fd == -1) {
        perror("inotify_init1");
        exit(EXIT_FAILURE);
    }
    /* Allocate memory for watch descriptors. */
    wd = calloc(argc, sizeof(int));
    if (wd == NULL) {
        perror("calloc");
        exit(EXIT_FAILURE);
    }
    /* Mark directories for events
       - file was opened
       - file was closed */
    for (i = 1; i < argc; i++) {
        wd[i] = inotify_add_watch(fd, argv[i], IN_OPEN | IN_CLOSE);
        if (wd[i] == -1) {
            fprintf(stderr, "Cannot watch '%s': %s\n", argv[i],
                    strerror(errno));
            exit(EXIT_FAILURE);
        }
    }
    /* Prepare for polling. */
    nfds = 2;
    fds[0].fd = STDIN_FILENO; /* Console input */
    fds[0].events = POLLIN;
    fds[1].fd = fd; /* Inotify input */
    fds[1].events = POLLIN;
    /* Wait for events and/or terminal input. */
    printf("Listening for events.\n");
    while (1) {
        poll_num = poll(fds, nfds, -1);
        if (poll_num == -1) {
            if (errno == EINTR) continue;
            perror("poll");
            exit(EXIT_FAILURE);
        }
        if (poll_num > 0) {
            if (fds[0].revents & POLLIN) {
                /* Console input is available. Empty stdin and quit. */
                while (read(STDIN_FILENO, &buf, 1) > 0 && buf != '\n') continue;
                break;
            }
            if (fds[1].revents & POLLIN) {
                /* Inotify events are available. */
                handle_events(fd, wd, argc, argv);
            }
        }
    }
    printf("Listening for events stopped.\n");
    /* Close inotify file descriptor. */
    close(fd);
    free(wd);
    exit(EXIT_SUCCESS);
}

输出:

$ ./a.out /tmp /home/user/temp
Press enter key to terminate.
Listening for events.
IN_OPEN: /home/user/temp/foo [file]
IN_CLOSE_WRITE: /home/user/temp/foo [file]
IN_OPEN: /tmp/ [directory]
IN_CLOSE_NOWRITE: /tmp/ [directory]

Listening for events stopped.
方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门
本栏推荐