CGR Localization
 All Classes Namespaces Files Functions Variables Macros Pages
watch_files.h
1 #ifndef _INCLUDED_WATCH_FILES_
2 #define _INCLUDED_WATCH_FILES_
3 
4 #include <sys/inotify.h>
5 
6 #include <vector>
7 
8 #include <unistd.h>
9 #include <fstream>
10 
11 #include "sstring.h"
12 
13 
14 class ActiveFile{
15 public:
16  CharString name;
17 protected:
18  time_t mod_time;
19 protected:
20  time_t getFileModTime();
21 public:
22  ActiveFile()
23  {mod_time=0;}
24 
25  void init(const char *_name)
26  {name=_name; mod_time=0;}
27  const char *operator()()
28  {return(name());}
29 
30  void invalidate()
31  {mod_time=0;}
32  bool isModified()
33  {return(mod_time != getFileModTime());}
34  void markAsRead()
35  {mod_time = getFileModTime();}
36 };
37 
38 class WatchFiles{
39 protected:
40  static const uint32_t ModEvents = IN_CLOSE_WRITE|IN_MOVE_SELF;
41 
42 public:
43  class Watch{
44  protected:
45  WatchFiles *parent;
46  int wd; // watch descriptor
47  public:
48  Watch()
49  {parent=NULL; wd=-1;}
50  Watch(const Watch &w)
51  {parent=w.parent; wd=w.wd;}
52 
53  bool valid()
54  {return(parent!=NULL && wd>=0);}
55  bool watch(WatchFiles *_parent,const char *filename)
56  {return(_parent && _parent->addWatch(*this,filename));}
57  bool rewatch(const char *filename)
58  {return(parent && parent->addWatch(*this,filename));}
59  bool remove()
60  {return(parent && parent->removeWatch(*this));}
61 
62  bool isFileModified()
63  {return(parent && (parent->calcEventMask(*this) & ModEvents));}
64 
65  friend class WatchFiles;
66  };
67 
68 protected:
69  std::vector<inotify_event> events;
70  int inotify_fd;
71  int num_watches;
72 public:
73  WatchFiles()
74  {inotify_fd=-1; num_watches=0;}
75  ~WatchFiles()
76  {reset();}
77 
78  bool init();
79  void reset();
80  bool isInited()
81  {return(inotify_fd >= 0);}
82 
83  bool addWatch(Watch &w,const char *filename);
84  bool removeWatch(Watch &w);
85  uint32_t calcEventMask(Watch &w);
86 
87  int getEvents();
88  int getNumEvents()
89  {return(events.size());}
90  void clearEvents()
91  {events.clear();}
92 };
93 
94 #endif