溫馨提示×

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錯誤。

五、參考資源

  • Linux官方文檔man inotify(需安裝manpages-dev包)。
  • API頭文件/usr/include/linux/inotify.h(包含事件類型和函數原型)。
  • 編程示例: 提供了C和Python的完整代碼示例。

通過以上步驟,可在Ubuntu系統中高效使用inotify API實現文件系統監控。

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女