KQUEUE(2)
okay so this is KQUEUE(2) from the System Calls Manual, and bestie, it is literally the kernel event notification mechanism. Buckle up. π β¨
πΈ NAME πΈ
kqueue, kevent β kernel event notification mechanism
π LIBRARY π
Standard C Library (libc, -lc) β iconic, no notes. π«Ά
π SYNOPSIS π
okay bestie, hereβs the exact shape of it:
#include <sys/event.h>
int
kqueue(void);
int
kqueuex(u_int flags);
int
kqueue1(int flags);
int
kevent(int kq, const struct kevent *changelist, int nchanges,
struct kevent *eventlist, int nevents,
const struct timespec *timeout);
EV_SET(kev, ident, filter, flags, fflags, data, udata);
π DESCRIPTION π
okay so kqueue() is the system call that gives you a generic method of notifying the user when an event happens or a condition holds, based on the results of small pieces of kernel code termed filters. A kevent is identified by the (ident, filter) pair β there may only be one unique kevent per kqueue. no duplicates, periodt. π
The filter is executed upon the initial registration of a kevent in order to detect whether a preexisting condition is present, and itβs also executed whenever an event is passed to the filter for evaluation. If the filter determines that the condition should be reported, then the kevent is placed on the kqueue for the user to retrieve. main character energy for the kernel. β¨
The filter is also run when the user attempts to retrieve the kevent from the kqueue. If the filter indicates that the condition that triggered the event no longer holds, the kevent is removed from the kqueue and is not returned. no stale vibes allowed. π«Ά
Multiple events which trigger the filter do not result in multiple kevents being placed on the kqueue; instead, the filter will aggregate the events into a single struct kevent. Calling close() on a file descriptor will remove any kevents that reference the descriptor. cleanup ate. π
The kqueue() system call creates a new kernel event queue and returns a descriptor. The queue is not inherited by a child created with fork(2). However, if rfork(2) is called without the RFFDG flag, then the descriptor table is shared, which will allow sharing of the kqueue between two processes. iykyk. π
The kqueuex() system call also creates a new kernel event queue, and additionally takes a flags argument, which is a bitwise-inclusive OR of the following flags:
KQUEUE_CLOEXECβ The returned file descriptor is automatically closed onexecve(2).KQUEUE_CPONFORKβ When this flag is set, the created kqueue is copied into the child process onfork(2)calls.
The kqueue descriptor index of the new kqueue will be inherited by the child, that is, the numeric value of the descriptor will remain the same.
Copying is deep, that is, each registered event in the original kqueue is copied (and not shared) into the new kqueue. This is contrary to how other descriptor types are handled upon fork(2), where the copied file descriptor references the same file object as the source descriptor (shallow copy).
By default, in other words, when the flag is not set, kqueues from the parent are not copied on fork to the child process. The corresponding file descriptor indeces are unused in the child.
Registered events that reference file descriptors which are not duplicated on fork, are not copied into the new kqueue. For instance, if the event references a file descriptor opened with the O_CLOEXEC flag set, it is not copied. Similarly, if event references a kqueue opened without the KQUEUE_CPONFORK flag, the event is not copied. deep copy, no cap. π
The kqueue() system call is equivalent to calling kqueuex() with flags set to 0.
The kqueue1() function exists for compatibility with NetBSD. The flags argument accepts zero or more of the following values:
O_CLOEXECβ The returned file descriptor is automatically closed onexecve(2).
The kevent() system call is used to register events with the queue, and return any pending events to the user. The changelist argument is a pointer to an array of kevent structures, as defined in <sys/event.h>. All changes contained in the changelist are applied before any pending events are read from the queue. The nchanges argument gives the size of changelist. The eventlist argument is a pointer to an array of kevent structures. The nevents argument determines the size of eventlist. When nevents is zero, kevent() will return immediately even if there is a timeout specified unlike select(2). If timeout is a non-NULL pointer, it specifies a maximum interval to wait for an event, which will be interpreted as a struct timespec. If timeout is a NULL pointer, kevent() waits indefinitely. To effect a poll, the timeout argument should be non-NULL, pointing to a zero-valued timespec structure. The same array may be used for the changelist and eventlist. the way thatβs so useful, honestly. π
The EV_SET() macro is provided for ease of initializing a kevent structure.
The kevent structure is defined as:
struct kevent {
uintptr_t ident; /* identifier for this event */
short filter; /* filter for event */
u_short flags; /* action flags for kqueue */
u_int fflags; /* filter flag value */
int64_t data; /* filter data value */
void *udata; /* opaque user data identifier */
uint64_t ext[4]; /* extensions */
};
The fields of struct kevent are:
identβ Value used to identify this event. The exact interpretation is determined by the attached filter, but often is a file descriptor.filterβ Identifies the kernel filter used to process this event. The pre-defined system filters are described below.flagsβ Actions to perform on the event.fflagsβ Filter-specific flags.dataβ Filter-specific data value.udataβ Opaque user-defined value passed through the kernel unchanged.extβ Extended data passed to and from kernel. The meaning of theext[0]andext[1]members is defined by the filter. If a filter does not use them, these members are passed through the kernel unchanged. Theext[2]andext[3]members are always passed through the kernel unchanged, providing additional user-defined values. extra lilβ pockets for your data. π
The flags field can contain the following values:
EV_ADDβ Adds the event to the kqueue. Re-adding an existing event will modify the parameters of the original event, and not result in a duplicate entry. Adding an event automatically enables it, unless overridden by theEV_DISABLEflag.EV_ENABLEβ Permitkevent()to return the event if it is triggered.EV_DISABLEβ Disable the event sokevent()will not return it. The filter itself is not disabled.EV_DISPATCHβ Disable the event source immediately after delivery of an event. SeeEV_DISABLEabove.EV_DELETEβ Removes the event from the kqueue. Events which are attached to file descriptors are automatically deleted on the last close of the descriptor.EV_RECEIPTβ This flag is useful for making bulk changes to a kqueue without draining any pending events. When passed as input, it forcesEV_ERRORto always be returned. When a filter is successfully added thedatafield will be zero. Note that if this flag is encountered and there is no remaining space ineventlistto hold theEV_ERRORevent, then subsequent changes will not get processed.EV_ONESHOTβ Return only the first occurrence of the filter being triggered. After the user retrieves the event from the kqueue, it is deleted.EV_CLEARβ Reset the state of the event after it is retrieved by the user. This is useful for filters which report state transitions instead of the current state. Note that some filters may automatically set this flag internally.EV_EOFβ Filters may set this flag to indicate filter-specific EOF condition.EV_ERRORβ See βRETURN VALUESβ below.EV_KEEPUDATAβ Preserve theudataassociated with an existing event. This allows other aspects of the event to be modified without requiring the caller to know theudatavalue previously registered with the event. This is especially useful withNOTE_TRIGGERorEV_ENABLE. This flag may not be used withEV_ADD. sneaky but valid. π
The predefined system filters are listed below. Arguments may be passed to and from the filter via the fflags and data fields in the kevent structure.
π EVFILT_READ
Takes a descriptor as the identifier, and returns whenever there is data available to read. The behavior of the filter is slightly different depending on the descriptor type.
Sockets β Sockets which have previously been passed to listen(2) return when there is an incoming connection pending. data contains the size of the listen backlog.
Other socket descriptors return when there is data to be read, subject to the SO_RCVLOWAT value of the socket buffer. This may be overridden with a per-filter low water mark at the time the filter is added by setting the NOTE_LOWAT flag in fflags, and specifying the new low water mark in data. On return, data contains the number of bytes of protocol data available to read.
If the read direction of the socket has shutdown, then the filter also sets EV_EOF in flags, and returns the socket error (if any) in fflags. It is possible for EOF to be returned (indicating the connection is gone) while there is still data pending in the socket buffer. the drama of it all. π
Vnodes β Returns when the file pointer is not at the end of file. data contains the offset from current position to end of file, and may be negative. negative offsets are valid and a lilβ mysterious. π¦
Okay so, real talk: this behavior is different from poll(2), where read events are triggered for regular files unconditionally. You can trigger this event unconditionally by setting the NOTE_FILE_POLL flag in fflags. β¨
Fifos, Pipes β returns when there is data to read; data contains the number of bytes available. When the last writer disconnects, the filter will set EV_EOF in flags. That gets cleared by the filter when a new writer connects, and at that point the filter will resume waiting for data to become available before returning. π«Ά
BPF devices β returns when the BPF buffer is full, the BPF timeout has expired, or when the BPF has βimmediate modeβ enabled and there is any data to read; data contains the number of bytes available. π
Eventfds β returns when the counter is greater than 0; data contains the counter value, which must be cast to uint64_t. π’
Kqueues β returns when pending events are present on the queue; data contains the number of events available. π
π
EVFILT_WRITE β write-ready energy
Takes a descriptor as the identifier, and returns whenever it is possible to write to the descriptor. For sockets, pipes and fifos, data will contain the amount of space remaining in the write buffer. The filter will set EV_EOF when the reader disconnects, and for the fifo case, this will be cleared when a new reader connects. π¨ Heads up: this filter is not supported for vnodes.
For sockets, the low water mark and socket error handling is identical to the EVFILT_READ case.
For eventfds, data will contain the maximum value that can be added to the counter without blocking.
For BPF devices, when the descriptor is attached to an interface the filter always indicates that it is possible to write and data will contain the MTU size of the underlying interface.
π«Ά EVFILT_EMPTY β empty write buffer check
Takes a descriptor as the identifier, and returns whenever there is no remaining data in the write buffer.
π§ EVFILT_AIO β async I/O events
Events for this filter are not registered with kevent() directly but are registered via the aio_sigevent member of an asynchronous I/O request when it is scheduled via an asynchronous I/O system call such as aio_read(). The filter returns under the same conditions as aio_error(). For more details on this filter see sigevent(3) and aio(4).
π EVFILT_VNODE β file vibes watchdog
Takes a file descriptor as the identifier and the events to watch for in fflags, and returns when one or more of the requested events occurs on the descriptor. The events to monitor are:
NOTE_ATTRIBβ the file referenced by the descriptor had its attributes changed.NOTE_CLOSEβ a file descriptor referencing the monitored file was closed. The closed file descriptor did not have write access.NOTE_CLOSE_WRITEβ a file descriptor referencing the monitored file was closed. The closed file descriptor had write access.- β οΈ This note, as well as
NOTE_CLOSE, are not activated when files are closed forcibly byunmount(2)orrevoke(2). Instead,NOTE_REVOKEis sent for such events.
- β οΈ This note, as well as
NOTE_DELETEβ theunlink()system call was called on the file referenced by the descriptor.NOTE_EXTENDβ for regular file, the file referenced by the descriptor was extended.- For directory, reports that a directory entry was added or removed, as the result of rename operation. The
NOTE_EXTENDevent is not reported when a name is changed inside the directory.
- For directory, reports that a directory entry was added or removed, as the result of rename operation. The
NOTE_LINKβ the link count on the file changed. In particular, theNOTE_LINKevent is reported if a subdirectory was created or deleted inside the directory referenced by the descriptor.NOTE_OPENβ the file referenced by the descriptor was opened.NOTE_READβ a read occurred on the file referenced by the descriptor.NOTE_RENAMEβ the file referenced by the descriptor was renamed.NOTE_REVOKEβ access to the file was revoked viarevoke(2)or the underlying file system was unmounted.NOTE_WRITEβ a write occurred on the file referenced by the descriptor.
On return, fflags contains the events which triggered the filter. π
π₯ EVFILT_PROC β process stalking (respectfully)
Takes the process ID to monitor as the identifier and the events to watch for in fflags, and returns when the process performs one or more of the requested events. If a process can normally see another process, it can attach an event to it. The events to monitor are:
NOTE_EXITβ the process has exited. The exit status will be stored indatain the same format as the status returned bywait(2).NOTE_FORKβ the process has calledfork().NOTE_EXECβ the process has executed a new process viaexecve(2)or a similar call.NOTE_TRACKβ follow a process acrossfork()calls. The parent process registers a newkeventto monitor the child process using the samefflagsas the original event. The child process will signal an event withNOTE_CHILDset infflagsand the parent PID indata.- If the parent process fails to register a new
kevent(usually due to resource limitations), it will signal an event withNOTE_TRACKERRset infflags, and the child process will not signal aNOTE_CHILDevent.
- If the parent process fails to register a new
On return, fflags contains the events which triggered the filter.
π¦ EVFILT_PROCDESC β process descriptor watch
Takes the process descriptor created by pdfork(2) to monitor as the identifier and the events to watch for in fflags, and returns when the associated process performs one or more of the requested events. The events to monitor are:
NOTE_EXITβ the process has exited. The exit status will be stored indata.
On return, fflags contains the events which triggered the filter.
π EVFILT_SIGNAL β signal receipts
Takes the signal number to monitor as the identifier and returns when the given signal is delivered to the process. This coexists with the signal() and sigaction() facilities, and has a lower precedence. The filter will record all attempts to deliver a signal to a process, even if the signal has been marked as SIG_IGN, except for the SIGCHLD signal, which, if ignored, will not be recorded by the filter. Event notification happens after normal signal delivery processing. data returns the number of times the signal has occurred since the last call to kevent(). This filter automatically sets the EV_CLEAR flag internally. π
EVFILT_JAIL π¦
okay so this one is literally the jail-watcher filter. you pass the jail ID you wanna keep an eye on as the identifier, and the events you care about go in fflags. then it comes back to you whenever that jail does one (or more) of the things you asked about. and bestie, if a process can normally see a jail, it can attach an event to it β that's the vibe check. an identifier of zero means "watch my own jail, tyvm" π
the events you can monitor are:
NOTE_JAIL_SETβ the jail got changed viajail_set(2). slay, she's different now β¨NOTE_JAIL_ATTACHβ a process attached to the jail viajail_attach(2)or a similar call. the process ID gets stored indata. but heads up: if more than one process has attached since the last call tokevent(), thendatawill be zero πNOTE_JAIL_REMOVEβ the jail has been removed. gone, deleted, no more πNOTE_JAIL_CHILDβ a child of the watched jail got created. its jail ID gets stored indata. same caveat as above: if more than one jail has been created since the last call tokevent(),datawill be zero π«Ά
on return, fflags contains the events that triggered the filter. it'll also contain NOTE_JAIL_MULTI if more than one NOTE_JAIL_ATTACH or NOTE_JAIL_CHILD event has been received since the last call to kevent() β basically a little "hey, there was more than one" flag π
EVFILT_JAILDESC π
same energy, different handle: this one takes a jail descriptor returned by jail_set(2) or jail_get(2) as the identifier, with the events to watch for in fflags, and returns when the jail performs one or more of the requested events. the events to monitor and the resulting fflags are literally the same as those listed in EVFILT_JAIL above. iykyk π
EVFILT_TIMER β°
this is the arbitrary-timer filter, identified by ident. when you're adding a timer, data specifies the moment to fire the timer (for NOTE_ABSTIME) or the timeout period. the timer is periodic unless you specify EV_ONESHOT or NOTE_ABSTIME. on return, data contains the number of times the timeout has expired since the last call to kevent(). and for non-monotonic timers, this filter automatically sets the EV_CLEAR flag internally β no cap, it just does it β¨
the filter accepts the following flags in the fflags argument:
NOTE_SECONDSβdatais in secondsNOTE_MSECONDSβdatais in millisecondsNOTE_USECONDSβdatais in microsecondsNOTE_NSECONDSβdatais in nanosecondsNOTE_ABSTIMEβ the specified expiration time is absolute
if fflags is not set, the default is milliseconds. on return, fflags contains the events which triggered the filter π―
periodic timers with a specified timeout of 0 will be silently adjusted to timeout after 1 of the time units specified by the requested precision in fflags. and if an absolute time is specified that has already passed, then it's treated as if the current time were specified, and the event will fire as soon as possible β she's not waiting around π
if an existing timer is re-added, the existing timer will be effectively canceled (throwing away any undelivered record of previous timer expiration) and re-started using the new parameters contained indataandfflags. so yeah, re-adding = a fresh start π¦
also there's a system wide limit on the number of timers, and it's controlled by the kern.kq_calloutmax sysctl. keep that in mind, bestie πΈ
EVFILT_USER π§
establishes a user event identified by ident which is not associated with any kernel mechanism β it's triggered by user level code, main character energy only π the lower 24 bits of the fflags may be used for user defined flags and manipulated using the following:
NOTE_FFNOPβ ignore the inputfflagsNOTE_FFANDβ bitwise ANDfflagsNOTE_FFORβ bitwise ORfflagsNOTE_FFCOPYβ copyfflagsNOTE_FFCTRLMASKβ control mask forfflagsNOTE_FFLAGSMASKβ user defined flag mask forfflags
a user event is triggered for output with the following:
NOTE_TRIGGERβ cause the event to be triggered π₯
on return, fflags contains the user defined flags in the lower 24 bits. periodt π
π CANCELLATION BEHAVIOUR π
if nevents is non-zero β i.e. the function is potentially blocking β the call is a cancellation point. otherwise, i.e. if nevents is zero, the call is not cancellable. cancellation can only occur before any changes are made to the kqueue, or when the call was blocked and no changes to the queue were requested. so like, timing matters, bestie π«Ά
β¨ RETURN VALUES β¨
the kqueue() system call creates a new kernel event queue and returns a file descriptor. if there was an error creating the kernel event queue, a value of -1 is returned and errno set. π
the kevent() system call returns the number of events placed in the eventlist, up to the value given by nevents. if an error occurs while processing an element of the changelist and there is enough room in the eventlist, then the event will be placed in the eventlist with EV_ERROR set in flags and the system error in data. otherwise, -1 will be returned, and errno will be set to indicate the error condition. if the time limit expires, then kevent() returns 0. iconic behaviour, honestly β
π EXAMPLES π
#include <sys/event.h>
#include <err.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int
main(int argc, char **argv)
{
struct kevent event; /* Event we want to monitor */
struct kevent tevent; /* Event triggered */
int kq, fd, ret;
if (argc != 2)
err(EXIT_FAILURE, "Usage: %s path\n", argv[0]);
fd = open(argv[1], O_RDONLY);
if (fd == -1)
err(EXIT_FAILURE, "Failed to open '%s'", argv[1]);
/* Create kqueue. */
kq = kqueue();
if (kq == -1)
err(EXIT_FAILURE, "kqueue() failed");
/* Initialize kevent structure. */
EV_SET(&event, fd, EVFILT_VNODE, EV_ADD | EV_CLEAR, NOTE_WRITE,
0, NULL);
/* Attach event to the kqueue. */
ret = kevent(kq, &event, 1, NULL, 0, NULL);
if (ret == -1)
err(EXIT_FAILURE, "kevent register");
for (;;) {
/* Sleep until something happens. */
ret = kevent(kq, NULL, 0, &tevent, 1, NULL);
if (ret == -1) {
err(EXIT_FAILURE, "kevent wait");
} else if (ret > 0) {
if (tevent.flags & EV_ERROR)
errx(EXIT_FAILURE, "Event error: %s", strerror(event.data));
else
printf("Something was written in '%s'\n", argv[1]);
}
}
/* kqueues are destroyed upon close() */
(void)close(kq);
(void)close(fd);
}
π ERRORS π
the kqueue() system call fails if:
[ENOMEM]β the kernel failed to allocate enough memory for the kernel queue π[ENOMEM]β theRLIMIT_KQUEUESrlimit (seegetrlimit(2)) for the current user would be exceeded[EMFILE]β the per-process descriptor table is full[ENFILE]β the system file table is full
the kevent() system call fails if:
[EACCES]β the process does not have permission to register a filter[EFAULT]β there was an error reading or writing thekeventstructure[EBADF]β the specified descriptor is invalid[EINTR]β a signal was delivered before the timeout expired and before any events were placed on the kqueue for return[EINTR]β a cancellation request was delivered to the thread, but not yet handled[EINVAL]β the specified time limit or filter is invalid[EINVAL]β the specified length of the event or change lists is negative[ENOENT]β the event could not be found to be modified or deleted[ENOMEM]β no memory was available to register the event or, in the special case of a timer, the maximum number of timers has been exceeded. this maximum is configurable via thekern.kq_calloutmaxsysctl[ESRCH]β the specified process to attach to does not exist
whenkevent()call fails withEINTRerror, all changes in thechangelisthave been applied. good to know, bestie π«Ά
π SEE ALSO π
aio_error(2), aio_read(2), aio_return(2), poll(2), read(2), select(2), sigaction(2), write(2), pthread_setcancelstate(3), signal(3)
Jonathan Lemon, βKqueue: A Generic and Scalable Event Notification Facilityβ, Proceedings of the FREENIX Track: 2001 USENIX Annual Technical Conference, USENIX Association, June 25-30, 2001.
πΈ HISTORY πΈ
the kqueue() and kevent() system calls first appeared in FreeBSD 4.1. the kqueuex() system call and kqueue1() function first appeared in FreeBSD 14.0. glow-up era β¨
π AUTHORS π
the kqueue subsystem and this manual page were written by Jonathan Lemon <jlemon@FreeBSD.org>. we stan π
π BUGS π
in versions older than FreeBSD 12.0, <sys/event.h> failed to parse without including <sys/types.h> manually. ancient history, but now you know π
and that's a wrap on the kqueue saga, bestie! this page is from the Debian fam, dated January 24, 2026, and it's literally KQUEUE(2) β go forth and watch those events πβ¨π¦
π¦ where this page comes from
- freebsd 15.1: base 15.1
- Copyright (c) 2000 Jonathan Lemon
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms