Search code examples
cmacosbsdkqueue

kqueue watch size change on directory


I'm trying to watch for size change on directory using kqueue, is this possible? The reason for this because I am watching directories and whenever an event triggers, I stat the directory and compare last mod times etc to figure out if contents-modifed, added, removed, or renamed events happend. My goal is to get an even to trigger on directory when contents-modified happens on a file inside the directory, I couldn't accomplish that so we had an idea, we want to detect size change on directory, as if a contents-modified happend on a file within then the size of directory will change. Is this possible?

Thanks


Solution

  • You don't want/need to stat() the directory. You need to read the list of files in the directory each time kqueue says the directory was modified, and compare it to the list as it was the last time you read it. Only then will you know if a new file has appeared, or if a file has been removed, or if a file has been renamed (you will also need to keep track of the inode numbers for each file in the list to detect renames).

    If you want to further monitor for changes to each file then you also need to add events for each file in the directory and update this list of events each time the event for the directory file is signalled.

    FYI: This command-line utility does what you want, and can be built to use kqueue: https://github.com/emcrisostomo/fswatch