溫馨提示×

inotify如何檢測文件修改

小樊
43
2025-09-02 16:57:03
欄目: 編程語言

inotify 是 Linux 系統中的一個內核子系統,用于監控文件系統事件。要使用 inotify 檢測文件修改,你需要使用 Linux 提供的 inotify API。以下是一個簡單的示例,展示了如何使用 inotify 監控文件修改:

  1. 首先,確保你的系統已經安裝了 inotify-tools。在大多數 Linux 發行版中,可以使用以下命令安裝:
sudo apt-get install inotify-tools
  1. 創建一個名為 inotify_example.c 的 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];

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

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

    // 添加要監控的文件
    wd = inotify_add_watch( fd, argv[1], IN_MODIFY );
    if ( wd < 0 ) {
        perror("inotify_add_watch");
        return 1;
    }

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

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

        while ( i < length ) {
            struct inotify_event *event = ( struct inotify_event *) &buffer[i];
            if ( event->len ) {
                if ( event->mask & IN_MODIFY ) {
                    printf("File %s modified\n", event->name );
                }
            }
            i += EVENT_SIZE + event->len;
        }
        i = 0;
    }

    // 移除監控并關閉文件描述符
    inotify_rm_watch( fd, wd );
    close(fd);

    return 0;
}
  1. 編譯 C 文件:
gcc inotify_example.c -o inotify_example
  1. 運行編譯后的程序,監控指定文件的修改:
./inotify_example <filename>

<filename> 替換為你要監控的文件名。程序將輸出文件的修改事件。

注意:這個示例僅用于演示目的,實際應用中可能需要處理更多的錯誤情況和邊緣情況。

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