简体   繁体   中英

c++ inotify - watch multiple directories / subdirectories

First of all, if there is an easier way than using inotify, please tell me!

Basically what I would like to do is watching a root directory with inotify with these flags: IN_CREATE | IN_MODIFY | IN_DELETE. When it's IN_CREATE and IN_ISDIR I would like to watch that folder too. But the main thing I need is whether a file was created, deleted or modified even in subdirectories. Now I know I can just add multiple directories with inotify_add_watch(), but when I read the event->name how can I know which directory it belongs to? The inotify_event struct doesn't seem to hold that value. So if I have a structure like this:

/root

Then I create a directory "a":

/root/a

Then create a file:

/root/a/tmp.txt

When I read event->name it'll only say tmp.txt, but how can I know it is in the "a" subdirectory? How can I know what the watch descriptor was?

In inotify_event structure the name field contains the name of the object to which the event occurred, relative to wd. You need to get the absolute path of the parent directory and concatenate the name of the file/directory to get the full path. Also in Inotify_event structure the mask field, you can use the IN_ISDIR mask bit to know if the event that has occurred for that wd is a file or a directory.

This is from the inotify here

The name field is only present when an event is returned for a file inside a watched directory; it identifies the file pathname relative to the watched directory. This pathname is null-terminated, and may include further null bytes to align subsequent reads to a suitable address boundary.

Here's how I did it: I created a hashmap (QHash<int, QString> fd_to_path) during inotify_add_watch() time to couple the received wd with its corresponding directory string:

int wd = inotify_add_watch(...next_dir_path..);
if (wd != -1)
    fd_to_path.insert(wd, next_dir_path);

Then when reading the received inotify event after struct inotify_event *ev = (...); you just query the corresponding dir path with:

QString dir_path = fd_to_path.value(ev->wd);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM