问题
监控文件/目录变化
解决
使用inotify API
,它是Linux文件系统监控的API,包括文件或目录的创建、修改和删除。
使用步骤
- 使用
inotify_init()
创建一个inotify
实例; - 使用函数
inotify_add_watch()
添加要监控的目录或文件以及要监控的事件。我们需要指定诸如ON CREATE
,ON ACCESS
,ON MODIFY
这些事件; - 等待事件发生,读取缓存,缓存中包含一个或多个发生的事件,使用
read()
或者select()
; - 处理已经发生的事件,然后返回第3步等待新事件的发生,以此往复;
- 使用函数
inotify_rm_watch()
移除监视描述符; - 关闭
inotify
实例
示例
#include<stdio.h>
#include<sys/inotify.h>
#include<unistd.h>
#include<stdlib.h>
#include<signal.h>
#include<fcntl.h> // library for fcntl function
#define MAX_EVENTS 1024 /* Maximum number of events to process*/
#define LEN_NAME 16 /* Assuming that the length of the filename
won't exceed 16 bytes*/
#define EVENT_SIZE ( sizeof (struct inotify_event) ) /*size of one event*/