如何在文件打开时收到通知
How to get notified if a file is opened
因此,如果我有一个目录 /dir
,它可以包含任意数量的文件 N,并且这些文件可以位于 /dir
中的任何子目录中.如何查看 /dir
,以便在 dir
或其任何子目录中的文件打开时收到通知?我不想查看所有文件并检查是否为该文件获取了锁。
我看过 FSEvents,但我很确定我无法用它来完成。
适用于 macOS 操作系统
所以谁能指出我正确的方向或知道解决方案
您可以使用 kqueue
,并且根据您想要监控的事件,您可以获得 "notified",例如,在您的情况下,您可以使用 EVFILT_VNODE
过滤器:
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.
要获取您可以监控的所有事件的列表,请查看以下人员: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:
一种方法是编写内核扩展并使用 Apple 的 Kernel Authorisation (KAuth) 框架。
然后您将订阅 File Operation scope 和 KAUTH_FILEOP_OPEN 操作。
这还需要用户态应用程序与内核扩展进行通信,以接收文件操作通知,因此此方法将取决于您对监视文件的要求,这是否只是矫枉过正.
因此,如果我有一个目录 /dir
,它可以包含任意数量的文件 N,并且这些文件可以位于 /dir
中的任何子目录中.如何查看 /dir
,以便在 dir
或其任何子目录中的文件打开时收到通知?我不想查看所有文件并检查是否为该文件获取了锁。
我看过 FSEvents,但我很确定我无法用它来完成。
适用于 macOS 操作系统
所以谁能指出我正确的方向或知道解决方案
您可以使用 kqueue
,并且根据您想要监控的事件,您可以获得 "notified",例如,在您的情况下,您可以使用 EVFILT_VNODE
过滤器:
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.
要获取您可以监控的所有事件的列表,请查看以下人员: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:
一种方法是编写内核扩展并使用 Apple 的 Kernel Authorisation (KAuth) 框架。
然后您将订阅 File Operation scope 和 KAUTH_FILEOP_OPEN 操作。
这还需要用户态应用程序与内核扩展进行通信,以接收文件操作通知,因此此方法将取决于您对监视文件的要求,这是否只是矫枉过正.