【问题标题】:Monitor Directory for Changes监控目录的变化
【发布时间】:2010-10-05 10:01:09
【问题描述】:

很像similar SO question,我正在尝试监视 Linux 机器上的目录以添加新文件,并希望在这些新文件到达时立即处理它们。关于实现这一点的最佳方法的任何想法?

【问题讨论】:

    标签: linux unix file-io listeners


    【解决方案1】:

    首先确保已安装inotify-tools

    然后像这样使用它们:

    logOfChanges="/tmp/changes.log.csv" # Set your file name here.
    
    # Lock and load
    inotifywait -mrcq $DIR > "$logOfChanges" &
    IN_PID=$$
    
    # Do your stuff here
    ...
    
    # Kill and analyze
    kill $IN_PID
    while read entry; do
       # Split your CSV, but beware that file names may contain spaces too.
       # Just look up how to parse CSV with bash. :)
       path=... 
       event=...
       ...  # Other stuff like time stamps?
       # Depending on the event…
       case "$event" in
         SOME_EVENT) myHandlingCode path ;;
         ...
         *) myDefaultHandlingCode path ;;
    done < "$logOfChanges"
    

    或者,在inotifywait 上使用--format 而不是-c 也是一个想法。

    只需man inotifywaitman inotifywatch 了解更多信息。

    您也可以使用 incron 并使用它来调用处理脚本。

    【讨论】:

    • 谢谢,到目前为止最好的答案。我确信 inotify 有一些漂亮的东西,这就是它。就像一个魅力。
    【解决方案2】:

    fschange (Linux File System Change Notification) 是一个完美的解决方案,但它需要给你的内核打补丁

    【讨论】:

    • 注意文章顶部的警告,fschange is an alternative to inotify that [was] implemented before inotify became part of the mainline Linux kernel.
    【解决方案3】:

    inotify

    使用 inotify,您可以查看目录以创建文件。

    【讨论】:

    • Inotify 不支持递归监视目录,这意味着必须为每个子目录创建单独的 inotify 监视。请记住这一点。
    • 另见包incron及其man page。我不确定它如何处理子文件夹。
    • 不,incron 不处理子文件夹,它在适当的“indiegogo”活动中完全失败,并且 incron 在 2012 年打瞌睡。悲伤,但它走到了死胡同。我真的希望,inotify 会留下来 ;-)
    【解决方案4】:

    我想到的一个解决方案是创建一个“文件侦听器”和一个 cron 作业。我对此并不疯狂,但我认为它可以工作。

    【讨论】:

    • 如果你想尽快处理它们,没有办法绕过 inotify。
    猜你喜欢
    • 1970-01-01
    • 2011-08-18
    • 1970-01-01
    • 2011-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-11-30
    相关资源
    最近更新 更多