Linux – Can inotify be used to watch for a specific file to be created without monitoring the entire directory

inotifylinux

I want to be notified when a specific filename is created. I'm looking at inotify. The IN_CREATE flag is available for monitoring a directory for any changes within it, but I'd prefer not to monitor the entire directory since there may be a good deal of activity in that directory besides the file I'm interested in. Can this be done?

Best Answer

You cannot have the kernel only inform you of a change to a certain path. The reasons are a bit subtle:

  • In Linux, a file object exists independently of any name(s) it may have. Files' names are actually attributes of their containing directory, and a single file may be called by multiple names (see, hardlinking).

  • The kernel has to have something to attach inotify objects to; it cannot attach an object to a pathname since a pathname isn't a real filesystem object; you have to attach to the parent directory or the file that path describes. But you can't attach to the file, because you're watching to see if a file with a given name is created, not changes to a given file.

Theoretically, the kernel could implement an API that allows you to select events for a given pathname when adding a watch to a directory, much in the same way it allows you to select types of events. This would bloat the API, and the kernel would in the end be processing the same data and doing the same string comparison you would be doing in userspace.

Is there a noticeable performance hit to placing a watch on a very active directory? I'm not sure how active you mean; tens of files a second, hundreds, millions?

In any case, I would avoid access: it's always going to be racey. A file could be created and removed between calls to access, and calling access in a very tight loop is going to be slow, and is the kind of problem inotify was designed to solve.

Related Question