ubuntu

Ubuntu inotify如何检测文件修改

小樊
40
2025-06-17 12:57:53
栏目: 智能运维

在Ubuntu系统中,inotify是一个用于监控文件系统事件的Linux内核子系统。要使用inotify检测文件修改,你可以使用多种编程语言实现,比如C、Python等。以下是使用Python的inotify库来检测文件修改的方法:

  1. 首先,确保你已经安装了inotify库。如果没有安装,可以使用pip进行安装:
pip install inotify
  1. 创建一个Python脚本来监控文件修改:
import os
from inotify_simple import INotify, flags

# 初始化inotify实例
inotify = INotify()

# 监控的文件或目录路径
file_path = '/path/to/your/file'

# 添加监控事件
watch_flags = flags.MODIFY | flags.CLOSE_WRITE
wd = inotify.add_watch(file_path, watch_flags)

try:
    while True:
        # 读取事件
        for event in inotify.read():
            if event.mask & flags.MODIFY:
                print(f'File {event.name} was modified.')
            elif event.mask & flags.CLOSE_WRITE:
                print(f'File {event.name} was closed after being written.')
except KeyboardInterrupt:
    # 移除监控并退出
    inotify.rm_watch(wd)
    print('Monitoring stopped.')
  1. 运行这个脚本:
python your_script.py

这个脚本会监控指定的文件,当文件被修改或关闭写入时,它会打印出相应的消息。

请注意,inotify有一定的限制,比如监控的文件描述符数量和事件数量。如果你需要监控大量的文件或目录,可能需要调整系统设置或者使用更高级的工具,如fswatchwatchdog

0
看了该问题的人还看了