class Watcher def initialize @pid = ARGV[0] @handlers = [] end def register(&block) @handlers << block end def run last = nil loop do cur = File.readlink("/proc/#{@pid}/cwd") if cur != last @handlers.each do |h| h.call cur end end last = cur end end end if __FILE__ == $0 if !ARGV[0] STDERR.puts "Usage: ruby events.rb $$ &" exit 1 end w = Watcher.new w.register { |ev| puts "Got #{ev}" } w.run end