linux文件系统变化通知机制(inotify)
如果我们需要实时的了解一个文件夹或者目录的变化,我们可以使用linux文件系统变化通知机制(inotify),只要有变化,都会收到通知。
inotify是用来监视文件系统事件的机制,在linux 2.6.13内核中引入。
该机制可以用来监视文件和目录,当文件或目录发生变化时,内核会将文件或目录的变化发送给inotify文件描述符,在应用层只需调用read()就可以读取这些事件,非常的方便。更好的是,inotify文件描述符还可以使用select、poll、epoll这些接口来监听,当有事件发生是,inotify文件描述符会可读
1、api介绍
#include <sys/inotify.h>
/* Create and initialize inotify instance. */
int inotify_init (void);
(1) inotify_init()在内核中创建一个实体,并返回一个文件描述符fd。
(2) 成功的话返回文件描述符,失败返回-1。
/* Add watch of object NAME to inotify instance FD. Notify about events specified by MASK. */
int inotify_add_watch (int __fd, const char *__name, uint32_t __mask);
创建监视器要提供:
(1) inotify实例inotify_init返回的文件描述符:fd。
(2) 监视目标路径:name。
(3) 监视事件列表:mask。
(4) 如果成功,返回监视器描述符wd,否则返回-1。
/* Remove the watch specified by WD from the inotify instance FD. */
int inotify_rm_watch (int __fd, int __wd);
用于从监视器列表中删除一个监视器。
(1) fd为inotify_init返回的文件描述符。
(2) wd为inotify_add_watch返回监视器描述符。
(3) 返回值:0 成功,-1 失败。
2、事件结构体
/* Structure describing an inotify event. */
struct inotify_event
{
int wd; /* Watch descriptor. */
uint32_t mask; /* Watch mask. */
uint32_t cookie; /* Cookie to synchronize two events. */
uint32_t len; /* Length (including NULs) of name. */
char name;