温馨提示×

Debian inotify使用教程是什么

小樊
50
2025-09-13 09:59:48
栏目: 智能运维

Debian inotify 使用教程

一、安装工具

通过 apt 安装 inotify-tools(含命令行工具):

sudo apt update  
sudo apt install inotify-tools libinotify-dev  # 后者用于编程开发  

二、命令行工具使用

1. inotifywait(实时监控)
  • 基本用法:监控指定目录(如当前目录)的所有事件:

    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 秒后停止。

2. inotifywatch(事件统计)
  • 统计事件次数:监控目录并在指定时间后输出事件统计:
    inotifywatch -t 10 -e create,delete /path/to/directory  
    
    • -t 10:监控 10 秒;-e:指定事件类型。

三、编程接口使用(libinotify)

需安装开发包 libinotify-dev,通过代码实现监控逻辑(以 C 语言为例):

  1. 安装开发包
    sudo apt install libinotify-dev  
    
  2. 示例代码:监控当前目录的创建、修改事件:
    #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;  
    }  
    
  3. 编译运行
    gcc -o inotify_example inotify_example.c -linotify  
    ./inotify_example  
    

四、高级用法

  • 集成到脚本:结合 inotifywait 实现自动化操作(如文件同步、备份)。
  • 系统服务配置:通过 systemd 设置开机自启的监控服务。

注意事项

  • 监控大量文件可能消耗系统资源,建议缩小监控范围。
  • 确保运行用户对目标目录有读写权限。

参考资料:

0