Ubuntu inotify使用教程
一、inotify简介
inotify是Linux内核提供的文件系统事件监控机制,能实时监测文件或目录的创建、删除、修改、移动等操作。在Ubuntu中,通常通过inotify-tools工具包(提供命令行工具)或编程接口(如C语言)使用inotify。
二、安装inotify-tools
inotify-tools是Ubuntu下使用inotify的核心工具包,包含inotifywait(监控事件)和inotifywatch(统计事件)两个命令。安装步骤如下:
sudo apt update # 更新软件包列表
sudo apt install inotify-tools # 安装inotify-tools
安装完成后,可通过inotifywait --help验证是否成功。
三、使用inotifywait命令行工具
inotifywait用于实时监控文件系统事件,以下是常见用法:
1. 基本监控(持续模式)
监控指定目录的所有事件(默认监控第一层目录):
inotifywait -m /path/to/directory
-m:持续监控(不退出),直到手动终止(Ctrl+C)。
2. 监控特定事件
通过-e选项指定事件类型(可多选,用逗号分隔):
inotifywait -m -e create,delete,modify /path/to/directory
常用事件类型:
create:文件/目录创建;delete:文件/目录删除;modify:文件内容修改;moved_to:文件/目录移入;moved_from:文件/目录移出。
3. 递归监控子目录
使用-r选项递归监控指定目录及其所有子目录:
inotifywait -m -r /path/to/directory
4. 排除特定文件/目录
通过--exclude选项排除符合正则表达式的文件/目录(如排除.log文件):
inotifywait -m -r --exclude '\.log$' /path/to/directory
5. 自定义输出格式
使用--format选项定义输出内容(如显示文件路径和事件类型):
inotifywait -m -e create,delete --format '%w%f %e' /path/to/directory
%w:监控路径;%f:文件名;%e:事件类型。
6. 设置超时时间
通过-t选项设置监控超时时间(秒),超时后自动退出:
inotifywait -m -t 60 /path/to/directory
四、使用inotifywatch统计事件
inotifywatch用于统计指定时间内文件系统事件的发生次数,用法示例如下:
inotifywatch -m -r -t 60 /path/to/directory
-m:持续监控;-r:递归监控子目录;-t 60:监控60秒后输出统计结果(如各事件的发生次数)。
五、使用C API编程实现inotify
若需要更灵活的监控逻辑(如集成到应用程序),可使用C语言调用inotify API。以下是简单示例:
1. 包含头文件
#include
#include
#include
#include
#include
2. 创建inotify实例
int fd = inotify_init();
if (fd < 0) {
perror("inotify_init failed");
exit(EXIT_FAILURE);
}
inotify_init()创建inotify实例,返回文件描述符(fd)。
3. 添加监控路径
int wd = inotify_add_watch(fd, "/path/to/directory", IN_CREATE | IN_DELETE | IN_MODIFY);
if (wd < 0) {
perror("inotify_add_watch failed");
close(fd);
exit(EXIT_FAILURE);
}
inotify_add_watch()添加监控,参数说明:
fd:inotify实例文件描述符;"/path/to/directory":监控路径;IN_CREATE | IN_DELETE | IN_MODIFY:监控事件类型(可组合)。
4. 读取和处理事件
char buffer[4096];
ssize_t length = read(fd, buffer, sizeof(buffer));
if (length < 0) {
perror("read failed");
inotify_rm_watch(fd, wd);
close(fd);
exit(EXIT_FAILURE);
}
for (int i = 0; i < length; ) {
struct inotify_event *event = (struct inotify_event *)&buffer[i];
if (event->len) {
if (event->mask & IN_CREATE) {
printf("Created: %s\n", event->name);
}
if (event->mask & IN_DELETE) {
printf("Deleted: %s\n", event->name);
}
if (event->mask & IN_MODIFY) {
printf("Modified: %s\n", event->name);
}
}
i += sizeof(struct inotify_event) + event->len;
}
read(fd, buffer, sizeof(buffer)):阻塞读取事件(无事件时等待);struct inotify_event:内核返回的事件结构体,包含事件类型(mask)和文件名(name)。
5. 移除监控并关闭实例
inotify_rm_watch(fd, wd); // 移除监控
close(fd); // 关闭inotify实例
六、注意事项
- 系统限制:inotify受系统资源限制(如最大监控数量),可通过
/proc/sys/fs/inotify/max_user_watches调整(如echo 524288 | sudo tee /proc/sys/fs/inotify/max_user_watches); - 权限问题:监控目录需有读取权限;
- 性能影响:递归监控大量文件(如百万级)可能影响系统性能。
以上就是关于“Ubuntu inotify使用教程”的相关介绍,筋斗云是国内较早的云主机应用的服务商,拥有10余年行业经验,提供丰富的云服务器、租用服务器等相关产品服务。云服务器资源弹性伸缩,主机vCPU、内存性能强悍、超高I/O速度、故障秒级恢复;电子化备案,提交快速,专业团队7×24小时服务支持!
简单好用、高性价比云服务器租用链接:https://www.jindouyun.cn/product/cvm