The kernel queues (kqueue) and kernel events (kevent) mechanism is extremely powerful and flexible, allowing you to receive a stream of kernel-level events (including file modifications) and to define a set of filters that limit which events are delivered to your application.
To use kernel queues, you must do four things:
Create a kernel event queue by calling kqueue. This function returns a file descriptor for a newly allocated event queue.
Open a file descriptor for each file that you wish to watch.
Create a list of events to watch for. To do this, use the EV_SET to fill in the fields of a kernel event structure. The prototype is as follows:
EV_SET(&kev, ident, filter, flags, fflags, data, udata); |
The first argument, kev, is the address of the structure itself. The second, ident, contains a file descriptor for the file you are watching.
The third argument, filter, contains the name of the kernel filter whose results you want to see. For example, you can use EVFILT_VNODE to monitor vnode operations on the file.
The remaining arguments are all specific to a particular filter and are described in the manual page for kevent(2).
Call kevent in a loop. This function monitors the kernel event queue for events and stores them in a buffer that you provide. The prototype is as follows:
int kevent(int kq, const struct kevent *changelist, |
int nchanges, struct kevent *eventlist, |
int nevents, const struct timespec *timeout); |
Its arguments are (in order) the queue file descriptor, the list of events to watch for (from the previous step), the number of events in that list, temporary storage space for the resulting event data, the size of that storage, and a timeout.
On success, the kevent function returns the number of events returned. If the timeout expires before any event occurs, it returns 0. Depending on the nature of the error, errors may be reported either as an event with the EV_ERROR flag set and the system error stored in the data field or by returning -1 with the error stored in errno.
Last updated: 2008-03-11