0

So if I have a directory /dir which can contain any number of files N and these files can be in any sub-directory in /dir. How can I watch /dir such that I get notified when a file in dir or any of its sub-directories is opened? I don't want to watch all files and check if a lock is acquired for that file.

I have looked at FSEvents, but I am pretty sure that I cannot do it with that.

It is for the macOS operating system

So can anyone point me in the right direction or know a solution

Lars Nielsen
  • 2,005
  • 2
  • 25
  • 48

2 Answers2

1

You could use kqueue, and based on the events that you would like to monitor you could get "notified", for example in your case you could use the EVFILT_VNODE filter:

EVFILT_VNODE Takes a file descriptor as the identifier and the
             events to watch for in fflags, and returns when one
             or more of the requested events occurs on the
             descriptor.  

To get a list of all events you could monitor check the man: https://www.freebsd.org/cgi/man.cgi?query=kqueue&sektion=2 (The implementation is pretty similar in all the BSD's including macOS), check this answer to see some differences: https://stackoverflow.com/a/49521218/1135424

nbari
  • 25,603
  • 10
  • 76
  • 131
  • I may be wrong but don't I need to still add a watcher for all files and directories? – Lars Nielsen Aug 24 '18 at 08:25
  • @LarsNielsen "yes" you will need to implement something to wait for an event, hope this lines of code could give you an idea https://github.com/immortal/immortal/blob/master/kqueue.go#L9-L47 it checks for any changes within a directory, also check the flags when checking for changes in a file: https://github.com/immortal/immortal/blob/master/kqueue.go#L66 – nbari Aug 24 '18 at 08:30
  • 1
    `kqueue` is indeed very light and by far better than other solutions doing polling & `sleep` also seems to be supported in iOS. – nbari Aug 24 '18 at 08:44
  • I have a similar problem to the OP, but unfortunately `kqueue` won't help either of us. macOS doesn't seem to emit file open or close events with `EVFILT_VNODE` (see https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man2/kqueue.2.html). FSEvents doesn't handle those events either; it appears that using a kernel extension (as @TheDarkKnight suggests above) is the only mechanism to get file open/close events. – simpsora Sep 18 '19 at 00:48
1

One method would be to write a Kernel Extension and use Apple's Kernel Authorisation (KAuth) framework.

You'd then subscribe to the File Operation scope and the KAUTH_FILEOP_OPEN action.

This would also require a user-land application to communicate with the kernel extension, to receive the notifications of file operations, so this method would depend upon your requirements for watching the files as to whether or not this is just overkill.

TheDarkKnight
  • 27,181
  • 6
  • 55
  • 85