vsys. first checkin
[vsys.git] / dirwatcher.ml
1 open Inotify
2 open Fdwatcher
3 open Printf
4 open Globals
5
6 (* I don't know if a wd corresponding to a deleted directory is evicted or just
7  * leaks - fix implementation of rmdir accordingly
8  *)
9
10 let wdmap = Hashtbl.create 1024
11
12 let fd = Inotify.init ()
13
14 let handle_dir_event dirname evlist str = 
15     let fname = String.concat "/" [dirname;str] in
16         printf "File: %s. " fname;List.iter 
17                   (fun e -> 
18                      printf "Event: %s\n" (string_of_event e)) 
19                   evlist;
20         flush Pervasives.stdout
21
22 let add_watch dir events handler =
23   printf "Adding watch for %s\n" dir;
24   let wd = Inotify.add_watch fd dir events in
25       Hashtbl.add wdmap wd (dir,handler)
26
27 let asciiz s =
28   let rec findfirstnul str idx len =
29     if ((idx==len) || 
30       (str.[idx]==(char_of_int 0))) then idx
31       else
32         findfirstnul str (idx+1) len
33   in
34   let nulterm = findfirstnul s 0 (String.length s) in
35     String.sub s 0 nulterm
36
37 let receive_event (eventdescriptor:fd_and_fname) (bla:fd_and_fname) =
38   let (_,fd) = eventdescriptor in
39       let evs = Inotify.read fd in
40         List.iter (fun x->
41                 match x with
42                   | (wd,evlist,_,Some(str)) ->
43                       let purestr = asciiz(str) in
44                       let (dirname,handler) = 
45                         try Hashtbl.find wdmap wd with Not_found->printf "Unknown watch descriptor\n";raise Not_found
46                       in
47                         (
48                         match handler with
49                           | None->handle_dir_event dirname evlist purestr
50                           | Some(handler)->handler dirname evlist purestr
51                         )
52                   | _ -> ()) 
53           evs
54
55 let initialize () =
56   Fdwatcher.add_fd (None,fd) (None,fd) receive_event