inotify
是 Linux 系统提供的一种文件系统事件监控机制,可以实时监控文件或目录的变化,如创建、删除、修改等。以下是如何使用 inotify
实现实时监控的步骤:
inotify-tools
首先,确保你的系统上安装了 inotify-tools
。这是一个常用的工具集,包含 inotifywait
和 inotifywatch
命令。
在 Debian/Ubuntu 系统上:
sudo apt-get update
sudo apt-get install inotify-tools
在 CentOS/RHEL 系统上:
sudo yum install inotify-tools
inotifywait
监控文件或目录inotifywait
是一个命令行工具,可以用来等待并报告文件系统事件。
inotifywait -m /path/to/directory -e create,delete,modify
-m
:持续监控模式。/path/to/directory
:要监控的目录路径。-e
:指定要监控的事件类型,如 create
(创建)、delete
(删除)、modify
(修改)等。监控 /home/user/documents
目录下的所有文件变化:
inotifywait -m /home/user/documents -e create,delete,modify
你可以将 inotifywait
的输出重定向到一个脚本或程序中进行处理。
创建一个名为 monitor.sh
的脚本:
#!/bin/bash
MONITOR_DIR="/home/user/documents"
LOG_FILE="/var/log/inotify.log"
inotifywait -m -r -e create,delete,modify --format '%w%f %e' "$MONITOR_DIR" |
while read FILE EVENT
do
echo "$(date '+%Y-%m-%d %H:%M:%S') - $FILE - $EVENT" >> "$LOG_FILE"
# 在这里添加你的处理逻辑
done
-r
:递归监控子目录。--format '%w%f %e'
:自定义输出格式,显示文件路径和事件类型。赋予脚本执行权限并运行:
chmod +x monitor.sh
./monitor.sh
inotifywait
的高级选项inotifywait
提供了许多高级选项,可以根据需要进行配置。
-t
:设置超时时间(秒),超时后自动退出。--exclude
:排除特定文件或目录。--timefmt
:自定义时间格式。设置超时时间为 60 秒:
inotifywait -m -t 60 /home/user/documents -e create,delete,modify
inotify
的编程接口如果你需要在自己的应用程序中使用 inotify
,可以使用 Linux 提供的系统调用接口。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/inotify.h>
#include <unistd.h>
#define EVENT_SIZE ( sizeof (struct inotify_event) )
#define BUF_LEN ( 1024 * ( EVENT_SIZE + 16 ) )
int main(int argc, char **argv)
{
int length, i = 0;
int fd;
int wd;
char buffer[BUF_LEN];
fd = inotify_init();
if (fd < 0) {
perror("inotify_init");
}
wd = inotify_add_watch(fd, "/home/user/documents", IN_CREATE | IN_DELETE | IN_MODIFY);
if (wd < 0) {
perror("inotify_add_watch");
}
length = read(fd, buffer, BUF_LEN);
if (length < 0) {
perror("read");
}
while (i < length) {
struct inotify_event *event = (struct inotify_event *) &buffer[i];
if (event->len) {
if (event->mask & IN_CREATE) {
printf("File %s was created\n", event->name);
}
if (event->mask & IN_DELETE) {
printf("File %s was deleted\n", event->name);
}
if (event->mask & IN_MODIFY) {
printf("File %s was modified\n", event->name);
}
}
i += EVENT_SIZE + event->len;
}
(void) inotify_rm_watch(fd, wd);
(void) close(fd);
return 0;
}
编译并运行:
gcc -o inotify_example inotify_example.c
./inotify_example
通过以上步骤,你可以使用 inotify
实现对文件或目录的实时监控,并根据需要进行处理。