Skip site navigation (1)Skip section navigation (2)
Date:      Sat, 13 Aug 2022 09:51:32 -0700
From:      Craig Leres <leres@freebsd.org>
To:        meator <meator.dev@gmail.com>, freebsd-hackers@FreeBSD.org
Subject:   Re: How to monitor a directory in FreeBSD?
Message-ID:  <754a7f6d-8fbe-aae0-796b-e5c0e782fc4f@freebsd.org>
In-Reply-To: <652f3c12-388c-04d0-ebeb-753b76b2b742@gmail.com>
References:  <652f3c12-388c-04d0-ebeb-753b76b2b742@gmail.com>

next in thread | previous in thread | raw e-mail | index | archive | help

On 8/13/22 05:16, meator wrote:
> Hello. I'm working on a C program that needs to know whether files and 
> directories in a specific directory were added, modified or deleted. (It 
> should also be done recursively for all subdirectories, but to keep it 
> simple I don't take recursion into account. It shouldn't be that hard to 
> implement it after I will be able to monitor a directory nonrecursively.)
> 
> I don't have much experience with BSD programming but I know POSIX. I 
> have used inotify before for this purpose, but BSD doesn't have it so I 
> started looking for BSD alternatives. The internet lead me to kqueue. I 
> saw some criticism of it, but I don't need to monitor several thousands 
> of files, so I hope it will be usable for my use case.
> 
> The EVFILT_VNODE filter documentation in kqueue(2) doesn't really talk 
> about files and directories, it talks about file descriptors. Inotify on 
> the other hand is very explicit about handling files in the monitored 
> directory. Kqueue can still detect creation and deletion of files inside 
> the monitored directory with NOTE_WRITE for files and NOTE_LINK for 
> directories (at least I think, I made a little test program to test this).
> 
> This is useful, but I don't see any obvious way to identify a newly 
> created file inside the monitored directory. File creation would result 
> in NOTE_WRITE, but struct kevent doesn't have any "name" field (unlike 
> inotify) that would show which file was created. I would have to make a 
> list of directories and compare the old state with the current state to 
> see the file which was added.
> 
> Kqueue also doesn't seem to detect modification of files inside the 
> monitored directory. Does this mean that I would have to monitor every 
> single file in the directory to make this work?
> 
> I think this shows that kqueue isn't really meant to be used for 
> monitoring directory members. Is this true? Have I misunderstood something?

The way I've done it is is to use EVFILT_VNODE/NOTE_WRITE to tell me 
when the directory has changed and then roll my own opendir()/readdir() 
code to detect what (if anything) was added or deleted.

		Craig



Want to link to this message? Use this URL: <https://mail-archive.FreeBSD.org/cgi/mid.cgi?754a7f6d-8fbe-aae0-796b-e5c0e782fc4f>