#! /usr/local/bin/ruby # load the fam bindings require 'fam' class TraverseDirWatcher def initialize(_path) @path = _path @childwatchers = Array.new # open a connection to FAM @fam = Fam::Connection.new $0 # create watcher for child directory if FileTest.directory?(@path) puts "watch directory : #{@path}" dir = Dir.open(@path) while name = dir.read next if name == "." next if name == ".." # watch child directory childpath = @path + "/" + name if FileTest.directory?(childpath) childwatcher = TraverseDirWatcher.new(childpath) @childwatchers.push(childwatcher) end end end end def start_mon(_sleep) puts "start mon : #{@path}" @fam.monitor_dir(@path) @thread_mon = Thread.start { puts "thread start : #{@path}" start_time = Time.now loop { # if there are fam events pending, then process them if @fam.pending? ev = @fam.next_event targetfile = @path + "/" + ev.file case ev.code when Fam::Event::CHANGED # ignore child directory's change next if FileTest.directory?(targetfile) puts "File Changed(#{@path}) :" << targetfile when Fam::Event::DELETED # remove watcher of deleted dir @childwatchers.delete_if { |watcher| watcher.path == targetfile } puts "File Deleted(#{@path}) :" << targetfile when Fam::Event::CREATED # add watcher for created dir if FileTest.directory?(targetfile) newwatcher = TraverseDirWatcher.new(targetfile) newwatcher.start_mon(_sleep) @childwatchers.push(newwatcher) end puts "File Created(#{@path}) :" << targetfile end end sleep _sleep } } @childwatchers.each { |watcher| watcher.start_mon(_sleep) } end def stop_mon() @thread_mon.kill @childwatchers.each{ |watcher| watcher.stop_mon() } end attr_accessor :path end path = ARGV[0] mon = TraverseDirWatcher.new(path) mon.start_mon(1) loop{ sleep 10; }