Inotifyd

来自 阿尔派 Linux

使用案例

有时我们需要监控一个目录(或文件)并执行一些后处理/操作。与其轮询目录以查找更改,不如使用 inotify 监视特定文件夹或文件,并在其上下文中发生某些事件时收到通知。虽然 aports 中有一些围绕 inotify 设计的工具 (inotify-tools),但 alpine 有一个内置工具 inotifyd(busybox 的一部分),用于在文件系统事件发生时执行命令。下面是如何仅使用基础 alpine(busybox 和 openrc)设置监视文件夹的示例。

创建 OpenRC 服务脚本

内容 /etc/init.d/inotifyd

#!/sbin/openrc-run command=/sbin/inotifyd command_args="$INOTIFYD_ARGS" command_user="$INOTIFYD_USER" pidfile=/run/${RC_SVCNAME}.pid command_background=yes start_stop_daemon_args="--stdout /var/log/$RC_SVCNAME/${RC_SVCNAME}.log --stderr /var/log/$RC_SVCNAME/${RC_SVCNAME}.log" start_pre() { checkpath --directory --owner $INOTIFYD_USER --mode 0775 \ /var/log/$RC_SVCNAME }


内容 /etc/conf.d/inotifyd

INOTIFYD_ARGS="/usr/local/bin/myscript /home/username/watchdir:w" INOTIFYD_USER=username


内容 /usr/local/bin/myscript

#!/bin/sh event="$1" directory="$2" file="$3" # run some command based on an event case "$event" in w) echo "writable $file is closed in $directory";; *) echo "This will never happen as we only listen for w.";; esac

完成步骤

启动 inotifyd

# rc-service inotifyd start

现在复制一些文件到监视文件夹中,并检查 /var/log/inotifyd 中的服务日志。

在上面的示例中,我们仅监听文件关闭事件 (w)。如果您想监听更多事件,只需将它们依次添加即可。如果您想监听所有事件,只需从目录中删除所有附加的事件字母。

可能的 inotify 事件

Events:
        a       File is accessed
        c       File is modified
        e       Metadata changed
        w       Writable file is closed
        0       Unwritable file is closed
        r       File is opened
        D       File is deleted
        M       File is moved
        u       Backing fs is unmounted
        o       Event queue overflowed
        x       File can't be watched anymore
If watching a directory:
        y       Subfile is moved into dir
        m       Subfile is moved out of dir
        n       Subfile is created
        d       Subfile is deleted