温馨提示×

ubuntu inotify怎样监控

小樊
39
2026-10-10 13:15:14
栏目: 智能运维

在 Ubuntu 里,inotify 通常有两种使用方式:

  1. 直接用命令行工具(最常用)
  2. 写程序调用 inotify API(C / Python 等)

下面分别说明。


一、用命令行工具监控(推荐)

1️⃣ inotifywait(最常用)

inotifywait 来自 inotify-tools 包。

安装

sudo apt update
sudo apt install inotify-tools

基本用法

监控某个目录(不递归):

inotifywait /path/to/dir

监控并持续等待:

inotifywait -m /path/to/dir

监控文件创建、修改、删除:

inotifywait -m -e create -e modify -e delete /path/to/dir

递归监控子目录:

inotifywait -m -r /path/to/dir

示例:监控日志文件变化

inotifywait -m -e modify /var/log/syslog

常用事件:

  • create
  • modify
  • delete
  • move
  • attrib
  • close_write

2️⃣ inotifywatch(统计事件)

统计一段时间内事件数量:

inotifywatch -v -t 60 -r /path/to/dir

二、用 inotify 编程(高级)

C 示例(简化)

#include <sys/inotify.h>
#include <stdio.h>
#include <unistd.h>

int main() {
    int fd = inotify_init();
    int wd = inotify_add_watch(fd, "/tmp", IN_MODIFY | IN_CREATE);

    char buf[1024];
    while (1) {
        int len = read(fd, buf, sizeof(buf));
        printf("event!\n");
    }
}

Python 示例

import inotify.adapters

inotify = inotify.adapters.Inotify()
inotify.add_watch('/path/to/dir')

for event in inotify.event_gen():
    if event:
        print(event)

安装:

pip install inotify

三、常见问题

❗ inotify 监控数量限制

Ubuntu 默认限制较少,大量监控会报错:

Failed to watch ... No space left on device

查看限制:

cat /proc/sys/fs/inotify/max_user_watches

临时修改:

sudo sysctl fs.inotify.max_user_watches=524288

永久修改:

echo "fs.inotify.max_user_watches=524288" | sudo tee -a /etc/sysctl.conf
sudo sysctl -p

四、典型使用场景

  • 自动同步文件(rsync + inotify)
  • 热重载服务
  • 日志实时监控
  • 文件上传触发处理

如果你告诉我 具体监控什么(目录?文件?做什么动作),我可以给你更精确的命令或脚本。

0 踩