首页 > 编程技术 > C语言

使用Inotify 监控目录与文件的方法详解

发布时间:2020-4-25 17:46

1. 监控路径并打印所有发生在该路径的事件.
代码如下:
复制代码 代码如下:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <sys/inotify.h>
#include <unistd.h>
#define EVENT_NUM 12
char *event_str[EVENT_NUM] =
{
 "IN_ACCESS",
 "IN_MODIFY",
 "IN_ATTRIB",
 "IN_CLOSE_WRITE",
 "IN_CLOSE_NOWRITE",
 "IN_OPEN",
 "IN_MOVED_FROM",
 "IN_MOVED_TO",
 "IN_CREATE",
 "IN_DELETE",
 "IN_DELETE_SELF",
 "IN_MOVE_SELF"
};
int main(int argc, char *argv[])
{
 int fd;
 int wd;
 int len;
 int nread;
 char buf[BUFSIZ];
 struct inotify_event *event;
 int i;

 if(argc < 2)
 {
  fprintf(stderr, "%s path\n", argv[0]);
  return -1;
 }

 fd = inotify_init();
 if( fd < 0 )
 {
  fprintf(stderr, "inotify_init failed\n");
  return -1;
 }

 wd = inotify_add_watch(fd, argv[1], IN_ALL_EVENTS);
 if(wd < 0)
 {
  fprintf(stderr, "inotify_add_watch %s failed\n", argv[1]);
  return -1;
 }

 buf[sizeof(buf) - 1] = 0;
 while( (len = read(fd, buf, sizeof(buf) - 1)) > 0 )
 {
  nread = 0;
  while( len > 0 )
  {
   event = (struct inotify_event *)&buf[nread];
   for(i=0; i<EVENT_NUM; i++)
   {
    if((event->mask >> i) & 1)
    {
     if(event->len > 0)
      fprintf(stdout, "%s --- %s\n", event->name, event_str[i]);
     else
      fprintf(stdout, "%s --- %s\n", " ", event_str[i]);
    }
   }
   nread = nread + sizeof(struct inotify_event) + event->len;
   len = len - sizeof(struct inotify_event) - event->len;
  }
 }

 return 0;
}

运行 inotify_watch 监控一个目录:
复制代码 代码如下:

$ ./inotify_watch test/
...
  --- IN_OPEN
  --- IN_CLOSE_NOWRITE
.tmp.swp --- IN_CREATE
.tmp.swp --- IN_OPEN
.tmp.swpx --- IN_CREATE
.tmp.swpx --- IN_OPEN
.tmp.swpx --- IN_CLOSE_WRITE
.tmp.swpx --- IN_DELETE
.tmp.swp --- IN_CLOSE_WRITE
.tmp.swp --- IN_DELETE
.tmp.swp --- IN_CREATE
.tmp.swp --- IN_OPEN
.tmp.swp --- IN_MODIFY
  --- IN_OPEN
  --- IN_CLOSE_NOWRITE
.tmp.swp --- IN_MODIFY
...

从上面的结果可以看到在 test 目录中使用 vim 创建一个 tmp 文件, 产生很多的冗杂事件. 因此需要对监控的事件做出小范围的选择而不是 IN_ALL_EVENTS .
2. IN_MOVE_SELF 和 IN_DELETE_SELF 事件
由于个人水平, 曾经对这两个事件的含义并没有理解正确. 当监控 path 时( path可以是文件或目录),
复制代码 代码如下:

$ ./inotify_watch path

执行
复制代码 代码如下:

$ rm -f path

则发生 IN_DELETE_SELF 事件;
执行
复制代码 代码如下:

mv path path2

则发生 IN_MOVE_SELF 事件.
3. 监控目录和文件
监控目录中内容改变应监控的事件:
复制代码 代码如下:

IN_CREATE | IN_DELETE | IN_DELETE_SELF | IN_MODIFY | IN_MOVE_SELF | IN_MOVED_FROM | IN_MOVDED_TO

监控文件内容的改变应监控的事件:
复制代码 代码如下:

IN_DELETE_SELF | IN_MODIFY | IN_MOVE_SELF

标签:[!--infotagslink--]

您可能感兴趣的文章: