热门关键字:  PHP  Cisco  seo  网络广告 虚拟主机 中文域名
当前位置 :| 主页>服务器>Linux服务器>

使用Inotify 监控Linux 文件系统事件

来源:赛迪网技术社区 作者:Eli M. Dow  时间:2006-10-08 点击:

在简单应用程序中使用 inotify

为演示 inotify 的使用,我将展示如何为文件系统事件构造一个监控任意目录(或单个文件)的示例程序。我将站在一个较高的层次上来展示 inotify 使文件系统监控变得多么容易。

Main 方法

这个简单的示例向我们展示 inotify 在任意目录上设置监控是多么容易。稍后我们将看到主要的帮助器例程。您可以在本文的 下载 一节获取这些例子中使用的示例代码。

/* This program will take as argument a directory name and monitor it,
   printing event notifications to the console.
*/
int main (int argc, char **argv)
{
   /* This is the file descriptor for the inotify device */
   int inotify_fd;

   /* First we open the inotify dev entry */
   inotify_fd = open_inotify_dev();
   if (inotify_fd < 0)
   {
      return 0;
   }


   /* We will need a place to enqueue inotify events,
      this is needed because if you do not read events
      fast enough, you will miss them.
   */
   queue_t q;
   q = queue_create (128);


   /* Watch the directory passed in as argument
      Read on for why you might want to alter this for
      more efficient inotify use in your app.
   */
   watch_dir (inotify_fd, argv[1], ALL_MASK);
   process_inotify_events (q, inotify_fd);


   /* Finish up by destroying the queue, closing the fd,
      and returning a proper code
   */
   queue_destroy (q);
   close_inotify_dev (inotify_fd);
   return 0;
}

清单 1. 在目录上设置监控

重要的帮助器方法

以下是每个基于 inotify 的应用程序共同的最重要的帮助器例程:

为读取而打开 inotify 设备。

对从该设备读取的事件进行排队。

允许应用程序对事件通知进行有用处理的实际的每事件处理器。

我不会深入钻研事件排队的细节,因为我们能够使用一些策略来避免排队。提供的代码中就展示了一个这样的方法;更先进的多线程方法可以并且已经在其他地方实现。在那些实现中,读者线程简单地在 inotify 设备上执行 select(),然后将事件拷贝到一些线程共享的存储空间(或者一些像 Glib 的异步消息队列的东西),以后处理器线程会处理这里的事件。

/* This simply opens the inotify node in dev (read only) */
int open_inotify_dev ()
{
   int fd;

   fd = open("/dev/inotify", O_RDONLY);

   if (fd < 0)
   {
      perror ("open("/dev/inotify", O_RDONLY) = ");
   }

   return fd;
}

清单 2. 打开 inotify 设备

最新评论共有 0 位网友发表了评论
发表评论
评论内容:不能超过250字,需审核,请自觉遵守互联网相关政策法规。
用户名: 密码:
匿名?
注册