inotify
是 Linux 内核提供的一种文件系统事件监控机制,它可以实时监控文件或目录的变化,如创建、删除、修改等。在 Debian 上使用 inotify
通常需要借助一些工具或库,比如 inotify-tools
或者编程接口 libinotify
。
inotify-tools
是一组基于 inotify
的命令行工具,可以用来监控文件系统事件。
安装 inotify-tools
打开终端,运行以下命令来安装 inotify-tools
:
sudo apt-get update sudo apt-get install inotify-tools
使用 inotifywait
inotifywait
是 inotify-tools
中的一个命令,用于等待文件系统事件的发生。
例如,监控当前目录下所有文件的创建事件:
inotifywait -m -e create .
参数说明:
-m
:监控模式,持续监控而不是只执行一次。-e create
:指定要监控的事件类型,这里是指文件或目录的创建。.
:指定要监控的目录,.
表示当前目录。你可以根据需要监控多种事件,例如删除、修改等:
inotifywait -m -e create,delete,modify .
如果你需要在自己的程序中使用 inotify
,可以使用 libinotify
库。
安装 libinotify
在 Debian 上,你可以使用 apt-get
来安装 libinotify
的开发包:
sudo apt-get install libinotify-dev
编写程序
下面是一个简单的示例,展示如何使用 libinotify
监控文件变化:
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/inotify.h> #include <unistd.h> int main(int argc, char *argv[]) { int length, i = 0; int fd; int wd; char buffer[4096]; // 创建 inotify 实例 fd = inotify_init(); if (fd < 0) { perror("inotify_init"); return 1; } // 添加监控目录 wd = inotify_add_watch(fd, ".", IN_MODIFY | IN_CREATE | IN_DELETE); if (wd < 0) { perror("inotify_add_watch"); return 1; } // 监控事件 length = read(fd, buffer, sizeof(buffer)); if (length < 0) { perror("read"); return 1; } // 解析事件 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 += sizeof(struct inotify_event) + event->len; } // 移除监控 inotify_rm_watch(fd, wd); // 关闭 inotify 实例 close(fd); return 0; }
编译并运行这个程序:
gcc -o inotify_example inotify_example.c ./inotify_example
通过这些方法,你可以在 Debian 上使用 inotify
来监控文件系统的变化。