7 #include "watch_files.h"
10 static const bool Debug =
false;
22 time_t FileModTime(
const char *filename)
30 void SetNonBlocking(
int fd)
32 int flags = fcntl(fd, F_GETFL, 0);
33 if(flags < 0) flags = 0;
34 fcntl(fd, F_SETFL, flags|O_NONBLOCK);
39 time_t ActiveFile::getFileModTime()
41 return(FileModTime(name()));
46 bool WatchFiles::init()
50 inotify_fd = inotify_init();
51 if(inotify_fd < 0)
return(
false);
52 SetNonBlocking(inotify_fd);
57 void WatchFiles::reset()
60 printf(
"WatchFiles: reset (num=%d)\n",num_watches);
71 bool WatchFiles::addWatch(Watch &w,
const char *filename)
74 if(!isInited() && !init())
return(
false);
77 if(w.parent) removeWatch(w);
80 w.wd = inotify_add_watch(inotify_fd, filename, ModEvents);
81 if(w.wd < 0)
return(
false);
86 printf(
"WatchFiles: watching \"%s\" (wd=%d)\n",
93 bool WatchFiles::removeWatch(Watch &w)
95 if(w.parent !=
this)
return(
false);
98 printf(
"WatchFiles: removing wd=%d\n",w.wd);
101 int ret = inotify_rm_watch(inotify_fd, w.wd);
104 if(ret == 0) num_watches--;
109 uint32_t WatchFiles::calcEventMask(Watch &w)
112 for(
unsigned i=0; i<events.size(); i++){
113 if(events[i].wd == w.wd) mask |= events[i].mask;
118 int WatchFiles::getEvents()
120 static const int BufSize = 512;
125 int nr = read(inotify_fd,buf,BufSize);
127 printf(
"Read inotify: %d\n",nr);
129 if(nr < (
int)
sizeof(inotify_event))
break;
134 const inotify_event &e = *(inotify_event*)(buf+i);
136 i +=
sizeof(inotify_event) + e.len;
139 printf(
"WatchFiles: wd=%d ev=0x%X",e.mask,e.wd);
140 if(e.len) printf(
" len=%d name=\"%s\"",e.len,e.name);
146 return(events.size());