debian

Debian下inotify的API如何使用

小樊
50
2025-04-26 10:08:53
栏目: 智能运维

在Debian下使用inotify的API,你需要遵循以下步骤:

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

首先,确保你的系统已经安装了libinotify-dev库。如果没有,请运行以下命令来安装它:

sudo apt-get update
sudo apt-get install libinotify-dev
  1. 编写代码

创建一个名为inotify_example.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 <path_to_watch>\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("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实例
    inotify_rm_watch(fd, wd);
    close(fd);

    return 0;
}

这个示例程序会监视指定的目录,并在文件被创建、删除或修改时输出相应的消息。

  1. 编译代码

使用以下命令编译示例程序:

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

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

./inotify_example /path/to/watch

现在,当你在该目录中创建、删除或修改文件时,程序将输出相应的消息。

注意:这个示例程序会一直运行,直到你手动停止它(例如,通过按Ctrl+C)。在实际应用中,你可能需要添加一些逻辑来优雅地终止程序。

0
看了该问题的人还看了