How to be notified of file/directory change in C/C

2020-02-02 08:35发布

The subject says it all - normally easy and cross platform way is to poll, intelligently. But every OS has some means to notify without polling. Is it possible in a reasonably cross platform way? (I only really care about Windows and Linux, but I use mac, so I thought posix may help?)

标签: c++ c posix
7条回答
混吃等死
2楼-- · 2020-02-02 08:59

I believe OS X now has appropriate hooks/callbacks because they were needed for Spotlight indexing.

On linux you'll have the additional trouble that there are multiple file systems commonly used. If you need the functionality for only a limited amount of files/directories, I'd try about actively looking for modifications at regular intervals.

查看更多
Luminary・发光体
3楼-- · 2020-02-02 09:00

The Qt library has a QFileSystemWatcher class which provides cross platform notifications when a file changes. Even if you are not using Qt, because the source is available you could have a look at it as a sample for your own implementation. Qt has separate implementations for Windows, Linux and Mac.

查看更多
Anthone
4楼-- · 2020-02-02 09:00

libevent or libev seem to be what you want, though I haven't used them.

查看更多
家丑人穷心不美
5楼-- · 2020-02-02 09:02

Linux users can use inotify

inotify is a Linux kernel subsystem that provides file system event notification.

Some goodies for Windows fellows:

查看更多
走好不送
6楼-- · 2020-02-02 09:02

I don't think POSIX itself has facilities for that. The closest to cross-platform I've seen is FAM, which seems to work for Linux, BSD, and Irix, but I'm not how easy it would be to port it to Windows and MacOS.

查看更多
Rolldiameter
7楼-- · 2020-02-02 09:13

I've actually built this system before for use in a commercial C++ code base- as long as you don't need every weird thing under the sun, the Windows and POSIX systems have a lot of overlap you can abstract.

POSIX: Use inotify- it is a whole system literally built for this job
Windows: Use "change events". You have to build more of the glue and reporting yourself (all the APIs you need are available, there's just not the 1-stop-shopping inotify gives you).

The common things you can detect in your "notification thread" for forwarding events are:
1) Basically any invasive operation boost::filesystem supports, with the (possible) exception of modifying permissions. This is things like moving, creating, deleting, copying folders and files.
2) Reads and writes to files (esp. writes). Be aware that if you're using async I/O the notifications can show up out-of-order.
3) When a new volume comes in, such as somebody connecting a flash drive.

inotify especially gives you an insane level of fine-grained control, Windows less so. With inotify you can literally monitor everything the filesystem is doing in near-real time if you really want to. I know #3 is possible with both without polling, but be aware that it can be really tricky to get it working correctly- on either system.

查看更多
登录 后发表回答