通过 apt
安装 inotify-tools
(含命令行工具):
sudo apt update
sudo apt install inotify-tools libinotify-dev # 后者用于编程开发
基本用法:监控指定目录(如当前目录)的所有事件:
inotifywait -m .
-m
:持续监控模式;.
:当前目录路径。指定事件类型:仅监控创建、修改事件:
inotifywait -m -e create,modify /path/to/directory
支持事件:create
(创建)、delete
(删除)、modify
(修改)、move
(移动)等。
递归监控子目录:
inotifywait -m -r /path/to/directory
-r
:递归监控所有子目录。
输出格式化:自定义输出信息(如时间、路径、事件类型):
inotifywait -m -r -e create,modify --format '%T %w%f %e' --timefmt '%Y-%m-%d %H:%M:%S' /path
--format
:指定输出格式(如 %w%f
为完整路径+文件名)。超时设置:监控指定时长后自动退出(单位:秒):
inotifywait -t 60 -m /path
-t 60
:监控 60 秒后停止。
inotifywatch -t 10 -e create,delete /path/to/directory
-t 10
:监控 10 秒;-e
:指定事件类型。需安装开发包 libinotify-dev
,通过代码实现监控逻辑(以 C 语言为例):
sudo apt install libinotify-dev
#include <stdio.h>
#include <sys/inotify.h>
#define EVENT_SIZE (sizeof(struct inotify_event))
#define BUF_LEN (1024 * (EVENT_SIZE + 16))
int main() {
int fd = inotify_init();
if (fd < 0) { perror("inotify_init"); return 1; }
int wd = inotify_add_watch(fd, ".", IN_CREATE | IN_MODIFY);
if (wd < 0) { perror("inotify_add_watch"); return 1; }
char buffer[BUF_LEN];
read(fd, buffer, BUF_LEN); // 读取事件数据
// 解析事件
struct inotify_event *event = (struct inotify_event *)buffer;
if (event->mask & IN_CREATE) printf("File created: %s\n", event->name);
if (event->mask & IN_MODIFY) printf("File modified: %s\n", event->name);
inotify_rm_watch(fd, wd);
close(fd);
return 0;
}
gcc -o inotify_example inotify_example.c -linotify
./inotify_example
inotifywait
实现自动化操作(如文件同步、备份)。systemd
设置开机自启的监控服务。参考资料: