KQUEUE(2)

πŸ“¦
version 2.3.1 Β· 4 versions
, in ubuntu jammy, ubuntu noble

πŸ’– KQUEUE(2) πŸ’– β€” the manual page, but make it a vibe

okay bestie, welcome to the kqueue/kevent page. kqueue, kevent β€” kernel event notification mechanism. it's giving "the kernel will text you when stuff happens." let's get into it 🫢


✨ SYNOPSIS ✨

#include <sys/types.h>
#include <sys/event.h>
#include <sys/time.h>

int
kqueue(void);

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. the kqueue() system call is literally the generic way of telling the user "hey, an event happened" or "hey, a condition holds," and it figures that out based on the results of lil bits of kernel code called filters. a kevent is identified by the (ident, filter) pair β€” and there can only ever be one unique kevent per kqueue. one. no duplicates. periodt.

the filter runs the moment you first register a kevent, so it can detect whether a preexisting condition is already there, and it also runs any time an event gets passed to the filter to be evaluated. if the filter decides the condition should be reported, the kevent gets placed on the kqueue for you to retrieve. πŸ‘‘

the filter also runs when you try to retrieve the kevent from the kqueue. if the filter says the condition that triggered the event no longer holds, the kevent is removed from the kqueue and is not returned to you. bye.

multiple events triggering the filter do not result in multiple kevents piling up on the kqueue β€” instead, the filter aggregates the events into a single struct kevent. and calling close() on a file descriptor removes any kevents that reference that descriptor. automatic. slay.

kqueue() creates a brand 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 lets two processes share the kqueue between them. iykyk πŸ’…

the kevent() system call is what you use to register events with the queue and to get any pending events back out. 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() returns immediately even if there's a timeout specified β€” unlike select(2). if timeout is a non-NULL pointer, it specifies a maximum interval to wait for an event, interpreted as a struct timespec. if timeout is a NULL pointer, kevent() waits indefinitely. to effect a poll, timeout should be non-NULL, pointing at a zero-valued timespec structure. and yes, the same array can be used for both the changelist and the eventlist. efficient πŸ’…

the EV_SET() macro is provided for ease of initializing a kevent structure. cute, convenient.

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 */
        intptr_t  data;         /* filter data value */
        void      *udata;       /* opaque user data identifier */
};

the fields of struct kevent are:

  • ident β€” the value used to identify this event. the exact interpretation is determined by the attached filter, but often it's 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. the kernel literally does not care what's in there, it just carries it for you. iconic.

✨ THE flags FIELD ✨

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 the EV_DISABLE flag.
  • EV_ENABLE β€” permits kevent() to return the event if it is triggered.
  • EV_DISABLE β€” disables the event so kevent() will not return it. note: the filter itself is not disabled.
  • EV_DISPATCH β€” disables the event source immediately after delivery of an event. see EV_DISABLE above.
  • 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 forces EV_ERROR to always be returned. when a filter is successfully added the data field will be zero.
  • EV_ONESHOT β€” causes the event to return only the first occurrence of the filter being triggered. after the user retrieves the event from the kqueue, it is deleted. one and done, bestie.
  • EV_CLEAR β€” after the event is retrieved by the user, its state is reset. 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. πŸ‘€

🌈 THE PREDEFINED SYSTEM FILTERS 🌈

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. let's break it down.

Sockets

sockets which have previously been passed to listen() 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. messy but that's just how it is 😭

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.

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. this may be cleared by passing in EV_CLEAR, at which 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.


πŸ¦‹ EVFILT_WRITE

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 may be cleared by use of EV_CLEAR. note that this filter is not supported for vnodes or BPF devices.

for sockets, the low water mark and socket error handling is identical to the EVFILT_READ case.


πŸ¦‹ EVFILT_VNODE

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_DELETE β€” the unlink() system call was called on the file referenced by the descriptor.
  • NOTE_WRITE β€” a write occurred on the file referenced by the descriptor.
  • NOTE_EXTEND β€” the file referenced by the descriptor was extended.
  • NOTE_ATTRIB β€” the file referenced by the descriptor had its attributes changed.
  • NOTE_LINK β€” the link count on the file changed.
  • NOTE_RENAME β€” the file referenced by the descriptor was renamed.

on return, fflags contains the events which triggered the filter.


πŸ¦‹ EVFILT_SIGNAL

takes the signal number to monitor as the identifier and returns when the given signal is delivered to the process. this overrides the signal() and sigaction() facilities, and has a higher precedence. the filter will record all attempts to deliver a signal to a process, even if the signal has been marked as SIG_IGN. 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. it does that itself, no input needed from you πŸ’…


πŸ¦‹ EVFILT_TIMER

establishes an arbitrary timer identified by ident. when adding a timer, data specifies the timeout period and fflags can be set to one of the following:

  • NOTE_SECONDS β€” data is in seconds
  • NOTE_USECONDS β€” data is in microseconds
  • NOTE_NSECONDS β€” bestie, the data is in nanoseconds now. tiny little units. so precise. πŸ’…
  • NOTE_ABSOLUTE β€” data is an absolute timeout, not a relative one. it's giving "deadline, not countdown". ⏰

If fflags isn't set, the default is milliseconds. The timer will be periodic unless you specify EV_ONESHOT β€” so like, it keeps going unless you tell it to be a one-and-done girlboss. On return, data holds the number of times the timeout has expired since the last time you called kevent(). This filter automatically sets the EV_CLEAR flag internally, no input needed from you, she handles it. 🌸

Heads up: there's a system wide limit on how many timers can exist, and it's controlled by the kern.kq_calloutmax sysctl. so don't go feral. 🫢

✨ EVFILT_USER β€” the people's filter ✨

Establishes a user event identified by ident which is not associated with any kernel mechanism β€” it's purely triggered by user level code. it's giving self-made, no kernel needed, main character energy. πŸ‘‘

The lower 24 bits of the fflags may be used for user defined flags, and you manipulate them with these:

  • NOTE_FFNOP β€” ignore the input fflags. like, no thoughts, head empty. πŸ™ˆ
  • NOTE_FFAND β€” bitwise AND the fflags.
  • NOTE_FFOR β€” bitwise OR the fflags.
  • NOTE_COPY β€” copy the fflags. verbatim, no cap. πŸ“‹
  • NOTE_FFCTRLMASK β€” the control mask for fflags.
  • NOTE_FFLAGSMASK β€” the user defined flag mask for fflags.

A user event is triggered for output with this:

  • NOTE_TRIGGER β€” cause the event to be triggered. go off, make it happen. πŸ”₯

On return, fflags contains the user defined flags in the lower 24 bits. πŸ’–


πŸ’« RETURN VALUES πŸ’«

The kqueue() system call creates a brand new kernel event queue and hands you back a file descriptor. iconic. If there was an error creating the kernel event queue, a value of -1 is returned and errno gets set. 😭

The kevent() system call returns the number of events placed in the eventlist, up to the value you gave in nevents. If an error occurs while processing an element of the changelist and there's enough room in the eventlist, then the event gets placed in the eventlist with EV_ERROR set in flags and the system error in data. Otherwise, -1 is returned, and errno is set to indicate the error condition. And if the time limit expires? kevent() returns 0. she waited, nothing happened, moving on. πŸ’…


🚨 ERRORS 🚨

The kqueue() system call fails if:

  • [ENOMEM] β€” the kernel failed to allocate enough memory for the kernel queue. the kernel is broke, fr fr. πŸ’€
  • [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. sorry babe, not your filter. πŸ™…
  • [EFAULT] β€” there was an error reading or writing the kevent structure.
  • [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.
  • [EINVAL] β€” the specified time limit or filter is invalid.
  • [ENOENT] β€” the event could not be found to be modified or deleted. she's not here, bestie. 😭
  • [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. that maximum is configurable via the kern.kq_calloutmax sysctl. ⚠️
  • [ESRCH] β€” the specified process to attach to does not exist. ghosted. πŸ‘»

πŸ‘€ SEE ALSO πŸ‘€

aio_error(2), aio_read(2), aio_return(2), poll(2), read(2), select(2), sigaction(2), write(2), signal(3)

go read those too, they're the friend group. 🫢


πŸ¦‹ HISTORY πŸ¦‹

The kqueue() and kevent() system calls first appeared in FreeBSD 4.1. vintage, but still serving looks. ✨


πŸŽ€ AUTHORS πŸŽ€

The kqueue() system and this manual page were written by Jonathan Lemon <jlemon@FreeBSD.org>. absolute legend, we love him, no notes. πŸ‘‘


and that's the whole page, bestie!! πŸ’– this one came from Debian, dated September 17, 2010 β€” oldie but a goodie, still iconic, still slaying. now go write some event loops. periodt. πŸ’…βœ¨

πŸ“¦ where this page comes from