溫馨提示×

如何用inotify實現實時監控

小樊
47
2025-07-05 12:36:52
欄目: 編程語言

inotify 是 Linux 系統提供的一種文件系統事件監控機制,可以用來實時監控文件或目錄的變化。以下是使用 inotify 實現實時監控的基本步驟:

1. 安裝必要的庫

在大多數 Linux 發行版中,inotify 工具和庫已經預裝。如果沒有,可以使用包管理器進行安裝。

sudo apt-get install inotify-tools  # Debian/Ubuntu
sudo yum install inotify-tools      # CentOS/RHEL

2. 使用 inotifywait 命令

inotifywait 是一個命令行工具,可以用來監控文件或目錄的變化。

監控單個文件

inotifywait -m /path/to/file -e modify,attrib,close_write,move,create,delete

監控整個目錄

inotifywait -m /path/to/directory -e modify,attrib,close_write,move,create,delete

3. 使用 inotify API 編程

如果你需要在自己的應用程序中實現實時監控,可以使用 inotify API。

示例代碼(C語言)

#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 ) )

int main(int argc, char **argv) {
    int length, i = 0;
    int fd;
    int wd;
    char buffer[BUF_LEN];

    // 創建 inotify 實例
    fd = inotify_init();
    if (fd < 0) {
        perror("inotify_init");
    }

    // 添加監控目錄
    wd = inotify_add_watch(fd, "/path/to/directory", IN_MODIFY | IN_ATTRIB | IN_CLOSE_WRITE | IN_MOVE | IN_CREATE | IN_DELETE);
    if (wd < 0) {
        perror("inotify_add_watch");
    }

    // 監控事件
    while (1) {
        length = read(fd, buffer, BUF_LEN);
        if (length < 0) {
            perror("read");
        }

        while (i < length) {
            struct inotify_event *event = (struct inotify_event *) &buffer[i];
            if (event->len) {
                if (event->mask & IN_CREATE) {
                    printf("File %s was created.\n", event->name);
                } else if (event->mask & IN_DELETE) {
                    printf("File %s was deleted.\n", event->name);
                } else if (event->mask & IN_MODIFY) {
                    printf("File %s was modified.\n", event->name);
                } else if (event->mask & IN_ATTRIB) {
                    printf("File %s attributes were changed.\n", event->name);
                } else if (event->mask & IN_CLOSE_WRITE) {
                    printf("File %s was closed after being written to.\n", event->name);
                } else if (event->mask & IN_MOVE) {
                    printf("File %s was moved.\n", event->name);
                }
            }
            i += EVENT_SIZE + event->len;
        }
        i = 0;
    }

    // 移除監控并關閉 inotify 實例
    inotify_rm_watch(fd, wd);
    close(fd);

    return 0;
}

4. 處理事件

在監控過程中,你可以根據不同的事件類型執行相應的操作。例如,當檢測到文件創建時,可以自動備份文件;當檢測到文件刪除時,可以記錄日志等。

5. 注意事項

  • inotify 有監控數量的限制,可以通過調整內核參數來增加監控數量。
  • 監控大量文件或目錄時,可能會消耗較多的系統資源,需要進行優化。

通過以上步驟,你可以使用 inotify 實現對文件或目錄的實時監控。

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