[英]File change notifications for macOS using C++
I'm coding a macOS launch daemon (in C++) and I need to know when a certain file on local disk was changed.我正在编写一个 macOS 启动守护程序(使用 C++),我需要知道本地磁盘上的某个文件何时被更改。 Does the OS provide such notifications?
操作系统是否提供此类通知?
PS.附言。 I was trying to avoid polling that file for a change every N seconds in a loop.
我试图避免在循环中每 N 秒轮询一次该文件的更改。
While it is possible to achieve some success in monitoring file changes with kqueue, as proposed by Sam in comments, I would recommend to use other approach.虽然如 Sam 在评论中所建议的那样,使用 kqueue 可以在监视文件更改方面取得一些成功,但我建议使用其他方法。
Try to use the FSEvents API .尝试使用FSEvents API 。 It is much more convenient than old-style kqueue stuff and could be easy integrated into c++ code .
它比老式的 kqueue 东西方便得多,可以很容易地集成到c++ 代码中。 It is also from the CoreServices Framework, so it could be safely used in daemons on macOS (search by "Daemon-Safe Frameworks")
它也来自 CoreServices Framework,因此它可以安全地用于 macOS 上的守护进程(搜索“Daemon-Safe Frameworks”)
The most important part of it is to subscribe to the events of interest, to have a separate event loop, and to release all these things correctly once the job is done.其中最重要的部分是订阅感兴趣的事件,有一个单独的事件循环,并在工作完成后正确释放所有这些东西。
From the first look it seems you can make use of kFSEventStreamEventFlagItemModified flag.乍一看,您似乎可以使用kFSEventStreamEventFlagItemModified标志。
In both ways you will need to clarify for yourself, what kind of "file was changed" definitions are interesting for you and adjust the event flags accordingly.在这两种方式中,您都需要自己弄清楚,您对哪种“文件已更改”定义感兴趣,并相应地调整事件标志。
There is no NOTE_CLOSE_WRITE on macOS, by the way, however there are some other useful flags for your case.顺便说一下,macOS 上没有 NOTE_CLOSE_WRITE,但是对于您的情况还有一些其他有用的标志。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.