debian

Debian下inotify API使用技巧

小樊
44
2025-08-22 08:42:36
栏目: 智能运维

在Debian系统下,使用inotify API可以帮助您监控文件系统事件,例如文件或目录的创建、修改、删除等

  1. 安装必要的库和头文件:

在Debian系统中,您需要安装libinotify-dev库来使用inotify API。使用以下命令安装:

sudo apt-get update
sudo apt-get install libinotify-dev
  1. 创建一个C程序:

创建一个名为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 <directory>\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 | IN_CREATE | IN_DELETE );
    if ( wd < 0 )
    {
        perror( "inotify_add_watch" );
        return 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_CREATE )
                    printf( "The file %s was created.\n", event->name );
                else if ( event->mask & IN_DELETE )
                    printf( "The file %s was deleted.\n", event->name );
                else if ( event->mask & IN_MODIFY )
                    printf( "The file %s was modified.\n", event->name );
            }
            i += EVENT_SIZE + event->len;
        }
        i = 0;
    }

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

    return 0;
}
  1. 编译C程序:

使用以下命令编译inotify_example.c

gcc inotify_example.c -o inotify_example
  1. 运行程序:

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

./inotify_example /path/to/directory

现在,程序将监控指定目录中的文件系统事件,并在控制台输出相关信息。

注意:这个示例程序会一直运行,直到您手动停止它。您可以根据需要修改代码,例如添加信号处理程序以便在接收到特定信号时优雅地退出程序。

0
看了该问题的人还看了