ubuntu

Ubuntu inotify API使用指南

小樊
32
2025-08-13 20:07:45
栏目: 智能运维

Ubuntu inotify API 使用指南

一、基础环境准备

  1. 安装工具包

    • 安装 inotify-tools(命令行工具,非API,用于快速测试):
      sudo apt-get update && sudo apt-get install inotify-tools  
      
    • 若需编程使用,确保系统已加载 inotify 内核模块(现代Ubuntu默认支持):
      lsmod | grep inotify  # 检查模块是否加载  
      
  2. 关键系统参数

    • 查看监控限制(默认值可能较低,需根据需求调整):
      cat /proc/sys/fs/inotify/max_user_watches  # 单用户最大监控项数  
      cat /proc/sys/fs/inotify/max_user_instances  # 单用户最大实例数  
      
    • 临时修改限制(如调大监控项数):
      sudo sysctl -w fs.inotify.max_user_watches=524288  
      
      永久生效需修改 /etc/sysctl.conf 并执行 sysctl -p

二、API核心使用步骤(C语言示例)

  1. 创建inotify实例

    #include <sys/inotify.h>  
    int fd = inotify_init();  
    if (fd < 0) { perror("inotify_init failed"); exit(1); }  
    
  2. 添加监控路径

    // 监控目录(递归需手动处理子目录)  
    int wd = inotify_add_watch(fd, "/path/to/directory",  
                               IN_CREATE | IN_MODIFY | IN_DELETE);  
    if (wd < 0) { perror("inotify_add_watch failed"); exit(1); }  
    // 事件类型说明:  
    // IN_CREATE:文件/目录创建  
    // IN_MODIFY:文件内容修改  
    // IN_DELETE:文件/目录删除  
    // 更多事件类型见  
    
  3. 读取事件

    char buffer[1024];  
    ssize_t len = read(fd, buffer, sizeof(buffer));  
    if (len < 0) { perror("read failed"); exit(1); }  
    // 解析事件  
    struct inotify_event *event;  
    for (char *p = buffer; p < buffer + len; ) {  
        event = (struct inotify_event *)p;  
        if (event->len) {  
            printf("Event: %s, File: %s\n",  
                   (event->mask & IN_CREATE) ? "CREATE" : "MODIFY/DELETE",  
                   event->name);  
        }  
        p += sizeof(struct inotify_event) + event->len;  
    }  
    
  4. 清理资源

    inotify_rm_watch(fd, wd);  // 移除监控  
    close(fd);  // 关闭实例  
    

三、编程语言封装库(推荐)

  1. Python(使用inotify库)

    import inotify.adapters  
    notifier = inotify.adapters.Inotify()  
    notifier.add_watch('/path/to/directory',  
                       mask=inotify.constants.IN_CREATE |  
                             inotify.constants.IN_MODIFY |  
                             inotify.constants.IN_DELETE)  
    for event in notifier.event_gen():  
        if event is not None:  
            print(f"Event: {event[1].maskname}, File: {event[2]}")  
    
    • 优势:无需手动处理缓冲区,支持递归监控(需配合inotify-tools--recursive选项或库的特定方法)。
  2. 其他语言

    • Go:使用 github.com/fsnotify/fsnotify 库(跨平台,封装inotify)。
    • Java:使用 org.apache.commons.io.monitor 或第三方库。

四、注意事项

  1. 递归监控限制

    • inotify本身不支持递归监控目录树,需通过代码手动遍历子目录并逐个添加监控(如结合opendir/readdir)。
    • 工具层面可通过 inotifywait -r 实现递归(非API方式)。
  2. 性能优化

    • 避免监控过多文件(单个实例建议不超过10万个监控项)。
    • 事件处理需高效,避免阻塞(如使用非阻塞I/O或单独线程处理事件)。
  3. 权限问题

    • 确保程序对监控路径有读权限,否则会触发EACCES错误。

五、参考资源

通过以上步骤,可在Ubuntu系统中高效使用inotify API实现文件系统监控。

0
看了该问题的人还看了