1、需求
工程中需要对某个文件夹下的文件进行监控,文件、目录发生变化后需要进行处理;
普通的方法是通过循环不停遍历文件夹,但文件数量较多时,将导致判定时间较长,并且无法区分文件使用正在使用;
万幸是Linux2.6后提供了一种inotify 对文件系统进行监控,通过触发的方式告诉你文件的变化,从而代替以往循环遍历的方式;
2、接口
2.1 接口说明
1) int inotify_init(void);
创建 inotify 实例,该接口返回一个文件描述符,失败返回-1,跟socket一样,可以通过errno获取错误类型;
DESCRIPTION
inotify_init() initializes a new inotify instance and returns a file descriptor associated with a new inotify
event queue.
If flags is 0, then inotify_init1() is the same as inotify_init(). The following values can be bitwise ORed
in flags to obtain different behavior:
IN_NONBLOCK Set the O_NONBLOCK file status flag on the new open file description. Using this flag saves extra
calls to fcntl(2) to achieve the same result.
IN_CLOEXEC Set the close-on-exec (FD_CLOEXEC) flag on the new file descriptor. See the description of the
O_CLOEXEC flag in open(2) for reasons why this may be useful.
RETURN VALUE
On success, these system calls return a new file descriptor. On error, -1 is returned, and errno is set to
indicate the error.
2)int inotify_add_watch(int fd, const char *pathname, uint32_t mask);
加入需要监控的目录到 inotify 实例,并设置监控类型 mask;成功后返回该目录的Watch file descriptor,后续用于在事件中进行辨识;
DESCRIPTION
inotify_add_watch() adds a new watch, or modifies an existing watch, for the file whose location is specified
in pathname; the caller must have read permission for this file. The fd argument is a file descriptor refer-
ring to the inotify instance whose watch list is to be modified. The events to be monitored for pathname are
specified in the mask bit-mask argument. See inotify(7) for a description of the bits that can be set in
mask.
A successful call to inotify_add_watch() returns the unique watch descriptor associated with pathname for this
inotify instance. If pathname was not previously being watched by this inotify instance, then