问题
I encounter some problem when using inotify. I use inotify to monitor changes on files. Here is my code:
int fd = inotify_init();
int wd = inotify_add_watch(fd, "/root/temp", IN_ALL_EVENTS);
int bufSize = 1000;
char *buf = new char[bufSize];
memset(buf, 0, sizeof(buf));
int nBytes = read(fd, buf, bufSize - 1);
cout << nBytes << " bytes read" << endl;
inotify_event *eventPtr = (inotify_event *)buf;
int offset = 0;
while (offset < nBytes)
{
cout << eventPtr->mask << endl;
offset += sizeof(inotify_event) + eventPtr->len;
eventPtr = (inotify_event *)(buf + offset);
}
delete []buf;
If I delete "/root/temp" and re-create such a file, any changes to this file is not monitored by inotify, anyone how is this? Thanks.
cheng
回答1:
That's because inotify
monitors the underlying inode, not the filename. When you delete that file, the inode you're currently watching becomes invalid, therefore, you must invoke inotify_rm_watch
. If you want to monitor a new file with the same name, but a different inode, you must detect when it's created by monitoring its parent folder.
回答2:
The other two answers are correct. Another useful point is that inotify tells you when the watch is invalidated.
mask & IN_IGNORED
will be non-zero. IN_IGNORED
is set when:
"Watch was removed explicitly (inotify_rm_watch(2)) or automatically (file was deleted, or file system was unmounted)."
So, as noted, when this is set, you can rewatch the file (and/or the directory if the file has not yet been re-created).
回答3:
Whenever you use an API, READ THE DOCUMENTATION.
inotify works using the unique file identifer inode, not a filename. The entire Linux kernel works with inodes in fact. Filenames are only a means to look up inodes.
To get what you want you need to monitor the /root directory. It will report a creation event when a file is added. If that file is named "temp" then you can add a watch on that file.
来源:https://stackoverflow.com/questions/4665833/inotify-stops-monitoring-file-when-the-file-is-deleted-and-created-again