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

前端 未结 7 814
无人及你
无人及你 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: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.

提交回复
热议问题