Sandeep
Sandeep

Reputation: 1247

inotify does not raise DELETE_SELF if an open file-fd exists

I am trying to monitor a directory using inotify and I am registering for ALL the events. Now, I have a requirement in my project to track any MOVE_SELF operations performed on the directory, so that I should be able to detect to which new location has the monitored directory moved to. To achieve this I am storing a reference of open file-descrptor (int fd) of the monitored directory and when I get a MOVE_SELF, I try to get the new path using:

//code to store a reference of file-descrptor of the monitored sirectory
fd = open(watchPath.c_str(), O_RDONLY)    


//code to learn the new location of the moved directory
char fdpath[4096];
char path[4096];

sprintf(fdpath, "/proc/self/fd/%d", fd);
ssize_t sz = readlink(fdpath, path, sizeof(path) - 1); //Path will contain the new location after the move happens

But the side effect of this is, in case I delete the directory, I do not get DELETE_SELF event, because there is still an open file descriptor that I am holding. Could anyone suggest me on how to get around this issue?

Thanks, -Sandeep

Upvotes: 2

Views: 1558

Answers (1)

user1643723
user1643723

Reputation: 4192

In case someone stumbles into this issue: this is definitely an expected behavior. Inotify does not monitor "files", it monitors "file objects" (aka inodes). An inode does not get removed by kernel until all open file descriptors, pointing to it, are closed.

This is also why IN_DELETE/IN_DELETE_SELF does not get triggered if you remove one of several hard links to file (because hard links share the same inode).

You can partially work around the hard link issue by subscribing to IN_ATTRIB event: it is triggered when the reference count of inode changes (e.g. when one of hard links is deleted), so you can use it to check if the file still exist at the old path.

As for "open descriptors" issue — I am not aware of any workarounds. Personally, I just don't care. So what if your program temporarily de-synchronizes with disk contents? Even if inotify were completely flawless, you would still need occasional re-sync due to queue overruns and event races.

Upvotes: 3

Related Questions