溫馨提示×

inotify在Linux中如何使用

小樊
40
2025-05-17 22:09:17
欄目: 智能運維

inotify 是 Linux 內核提供的一種文件系統事件監控機制,可以用來監控文件或目錄的變化,如創建、刪除、修改等。inotify 主要通過以下幾個系統調用和 API 來使用:

1. 系統調用

inotify 提供了以下幾個主要的系統調用:

  • inotify_init(): 初始化一個 inotify 實例,返回一個文件描述符。
  • inotify_add_watch(): 添加一個監控項,指定要監控的文件或目錄以及感興趣的事件。
  • read(): 讀取 inotify 事件。
  • inotify_rm_watch(): 移除一個監控項。
  • close(): 關閉 inotify 文件描述符。

2. 使用示例

以下是一個簡單的示例,演示如何使用 inotify 監控一個目錄的變化:

#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];

    // 檢查命令行參數
    if (argc != 2) {
        printf("Usage: %s <directory>\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    // 初始化 inotify
    fd = inotify_init();
    if (fd < 0) {
        perror("inotify_init");
        exit(EXIT_FAILURE);
    }

    // 添加監控項
    wd = inotify_add_watch(fd, argv[1], IN_MODIFY | IN_CREATE | IN_DELETE);
    if (wd < 0) {
        perror("inotify_add_watch");
        exit(EXIT_FAILURE);
    }

    printf("Monitoring directory: %s\n", argv[1]);

    // 讀取事件
    while (1) {
        length = read(fd, buffer, BUF_LEN);
        if (length < 0) {
            perror("read");
            exit(EXIT_FAILURE);
        }

        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);
                }
            }
            i += EVENT_SIZE + event->len;
        }
        i = 0;
    }

    // 關閉 inotify 文件描述符
    close(fd);

    return 0;
}

3. 編譯和運行

使用 gcc 編譯上述代碼:

gcc -o inotify_example inotify_example.c

然后運行程序并監控一個目錄:

./inotify_example /path/to/directory

4. 注意事項

  • inotify 有監控數量的限制,可以通過 /proc/sys/fs/inotify/max_user_watches 文件查看和修改。
  • 監控大量文件或目錄時,可能需要優化代碼以處理更多的事件。
  • inotify 事件可能會被合并,因此需要仔細處理事件的順序和完整性。

通過這些步驟,你可以使用 inotify 在 Linux 中監控文件系統的變化。

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