linux

inotify在Linux中如何使用

小樊
40
2025-05-17 22:09:17
栏目: 智能运维

inotify 是 Linux 内核提供的一种文件系统事件监控机制,可以用来监控文件或目录的变化,如创建、删除、修改等。inotify 主要通过以下几个系统调用和 API 来使用:

1. 系统调用

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 在 Linux 中监控文件系统的变化。

0
看了该问题的人还看了