How to be notified of file/directory change in C/C++, ideally using POSIX

前端 未结 7 773
无人及你
无人及你 2020-12-08 04:40

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 reasonab

相关标签:
7条回答
  • 2020-12-08 05:09

    Linux users can use inotify

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

    Some goodies for Windows fellows:

    • File Change Notification on MSDN
    • "When Folders Change" article
    • File System Notification on Change
    0 讨论(0)
  • 2020-12-08 05:15

    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.

    0 讨论(0)
  • 2020-12-08 05:16

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

    0 讨论(0)
  • 2020-12-08 05:21

    There's File System Events API as of Leopard.

    0 讨论(0)
  • 2020-12-08 05:24

    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.

    0 讨论(0)
  • 2020-12-08 05:28

    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.

    0 讨论(0)
提交回复
热议问题