如何使用inotify实现文件变更通知

inotify 是 Linux 内核提供的一种文件系统事件监控机制,可以用来检测文件的创建、修改、删除等操作。以下是使用 inotify 实现文件变更通知的基本步骤:1. 安装必要的库首先,确保你的系统上安装了 libinotify 库。在大多数 Linux 发行版中,这个库是默认安装的。如果没有安装,可以使用包管理器进行安装:sudo apt-get install libinotify-

inotify 是 Linux 内核提供的一种文件系统事件监控机制,可以用来检测文件的创建、修改、删除等操作。以下是使用 inotify 实现文件变更通知的基本步骤:

1. 安装必要的库

首先,确保你的系统上安装了 libinotify 库。在大多数 Linux 发行版中,这个库是默认安装的。如果没有安装,可以使用包管理器进行安装:

sudo apt-get install libinotify-dev  # Debian/Ubuntu
sudo yum install libinotify-devel      # CentOS/RHEL

2. 编写代码

下面是一个使用 libinotify 库的简单示例代码,用于监控指定目录下的文件变更:

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

void print_event( struct inotify_event *event ) {
    printf( "Event type: %d\n", event->mask );
    if ( event->mask & IN_CREATE ) {
        printf( "File created: %s\n", event->name );
    }
    if ( event->mask & IN_DELETE ) {
        printf( "File deleted: %s\n", event->name );
    }
    if ( event->mask & IN_MODIFY ) {
        printf( "File modified: %s\n", event->name );
    }
    if ( event->mask & IN_MOVED_FROM ) {
        printf( "File moved from: %s\n", event->name );
    }
    if ( event->mask & IN_MOVED_TO ) {
        printf( "File moved to: %s\n", event->name );
    }
}

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( 1 );
    }

    // 创建 inotify 实例
    fd = inotify_init();
    if ( fd < 0 ) {
        perror( "inotify_init" );
        exit( 1 );
    }

    // 添加监控目录
    wd = inotify_add_watch( fd, argv[1], IN_CREATE | IN_DELETE | IN_MODIFY | IN_MOVED_FROM | IN_MOVED_TO );
    if ( wd < 0 ) {
        perror( "inotify_add_watch" );
        exit( 1 );
    }

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

    while ( 1 ) {
        length = read( fd, buffer, BUF_LEN );
        if ( length < 0 ) {
            perror( "read" );
            exit( 1 );
        }

        while ( i < length ) {
            struct inotify_event *event = ( struct inotify_event *)&buffer[i];
            print_event( event );
            i += EVENT_SIZE + event->len;
        }
        i = 0;
    }

    // 移除监控并关闭 inotify 实例
    inotify_rm_watch( fd, wd );
    close( fd );

    return 0;
}

3. 编译代码

使用 gcc 编译上述代码:

gcc -o inotify_example inotify_example.c -linotify

4. 运行程序

运行编译后的程序,并指定要监控的目录:

./inotify_example /path/to/directory

5. 解释代码

  • inotify_init():初始化 inotify 实例,返回文件描述符。
  • inotify_add_watch():添加监控目录,返回监控描述符(watch descriptor)。
  • read():读取 inotify 事件。
  • print_event():解析并打印事件信息。

通过上述步骤,你可以使用 inotify 实现对文件变更的实时通知。

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,请发送邮件至 55@qq.com 举报,一经查实,本站将立刻删除。转转请注明出处:https://www.szhjjp.com/n/1446466.html

(0)
派派
上一篇 2025-11-04
下一篇 2025-11-04

发表回复

登录后才能评论