inotify
是 Linux 系统提供的一种文件系统事件监控机制,可以用来监控文件或目录的变化,如创建、删除、修改等。以下是使用 inotify
实现文件监控的基本步骤:
在大多数 Linux 发行版中,inotify
工具和库已经预装。如果没有,可以使用包管理器进行安装。例如,在 Debian/Ubuntu 上:
sudo apt-get install inotify-tools libinotify-dev
下面是一个使用 C 语言和 libinotify
库的简单示例,展示如何监控一个目录中的文件变化。
libinotify
开发包sudo apt-get install libinotify-dev
#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 ) )
void monitor_directory(const char *path) {
int length, i = 0;
int fd = inotify_init();
if (fd < 0) {
perror("inotify_init");
return;
}
int wd = inotify_add_watch(fd, path, IN_MODIFY | IN_CREATE | IN_DELETE);
if (wd < 0) {
perror("inotify_add_watch");
close(fd);
return;
}
char buffer[BUF_LEN];
while (1) {
length = read(fd, buffer, BUF_LEN);
if (length < 0) {
perror("read");
break;
}
while (i < length) {
struct inotify_event *event = (struct inotify_event *) &buffer[i];
if (event->len) {
if (event->mask & IN_CREATE) {
printf("File %s created\n", event->name);
} else if (event->mask & IN_DELETE) {
printf("File %s deleted\n", event->name);
} else if (event->mask & IN_MODIFY) {
printf("File %s modified\n", event->name);
}
}
i += EVENT_SIZE + event->len;
}
i = 0;
}
(void) inotify_rm_watch(fd, wd);
(void) close(fd);
}
int main(int argc, char **argv) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <directory>\n", argv[0]);
return EXIT_FAILURE;
}
monitor_directory(argv[1]);
return EXIT_SUCCESS;
}
gcc -o monitor_directory monitor_directory.c -linotify
./monitor_directory /path/to/directory
inotify_init()
: 初始化 inotify
实例并返回文件描述符。inotify_add_watch()
: 添加一个监控项,指定要监控的路径和事件类型。read()
: 读取 inotify
事件。inotify_rm_watch()
: 移除监控项。close()
: 关闭文件描述符。如果你使用其他编程语言,如 Python,可以使用 pyinotify
库来实现类似的功能。
pyinotify
pip install pyinotify
import pyinotify
class EventHandler(pyinotify.ProcessEvent):
def process_IN_MODIFY(self, event):
print(f"File {event.pathname} modified")
def process_IN_CREATE(self, event):
print(f"File {event.pathname} created")
def process_IN_DELETE(self, event):
print(f"File {event.pathname} deleted")
def monitor_directory(path):
wm = pyinotify.WatchManager()
mask = pyinotify.IN_MODIFY | pyinotify.IN_CREATE | pyinotify.IN_DELETE
notifier = pyinotify.Notifier(wm, EventHandler())
wm.add_watch(path, mask, rec=True)
notifier.loop()
if __name__ == "__main__":
monitor_directory("/path/to/directory")
通过这些步骤,你可以使用 inotify
实现文件监控功能。根据你的需求,可以选择合适的编程语言和库来实现。