Kqueue Reference
Kqueue is the relevant macanism on BSD based Operating Systems. One example of this is Macos. Kqueue, similarely to Epoll, is a readiness based model.

Quick reference of important Kqueue syscalls

kqueue

Kqueue is a system call which provides us with a generic method which lets us get notified when an kernel event has occured. Similarely to the CreateCompletionPorton Windows this returns a handle to an event queue file descriptor.
Mac OS X Manual Page For kqueue(2)

kevent

In contrast to IOCP (and Epoll), we use the same syscall to register and wait for events. The kqueuesyscall will know what to do based on the arguments we provide. As we'll see, this results in a pretty elegant API but it can be a bit hard to wrap your head around in the start. It's documented on the same manpage as kqueue.

close

We need a way to close the file handle to our event queue. The closesyscall lets us do just that.

Important structures

Kevent(structure)

Not to be confused with the keventsyscall. This structure is the most important way for us to provide information to our keventsyscall what we want to do.
1
#[derive(Debug, Clone, Default)]
2
#[repr(C)]
3
pub struct Kevent {
4
/// Value used to identify this event. The exact interpretation
5
/// is determined by the attached filter, but often is a file descriptor.
6
pub ident: u64,
7
/// Identifies the kernel filter used to process this event.
8
pub filter: i16,
9
/// Actions to perform on the event
10
pub flags: u16,
11
/// Filter-specific flags
12
pub fflags: u32,
13
/// Filter-specific data value
14
pub data: i64,
15
/// Opaque user-defined value passed through the kernel unchanged
16
pub udata: u64,
17
}
Copied!
We'll explain the filters and flags we need to use when we show how to use kqueuein practice, but please note the udatafield. This lets us attach a value which is untouched by the OS. We need a way to identify which event that has occured and this field will be valuable for us.

Timespec

Timeouts on BSD is passed as a Timespecstruct. It's important for us since we want to be able to set a timeout for how long we want to wait for an event before the thread calling pollis woken up.
1
#[derive(Debug)]
2
#[repr(C)]
3
pub(super) struct Timespec {
4
/// Seconds
5
tv_sec: isize,
6
/// Nanoseconds
7
v_nsec: usize,
8
}
Copied!

Useful flags and constants

1
pub const EVFILT_READ: i16 = -1;
2
pub const EVFILT_TIMER: i16 = -7;
3
pub const EV_ADD: u16 = 0x1;
4
pub const EV_ENABLE: u16 = 0x4;
5
pub const EV_ONESHOT: u16 = 0x10;
6
pub const EV_CLEAR: u16 = 0x20;
Copied!
The exact meaning of these is described in the Kqueuemanpage. However, getting the actual values can be pretty hard so I've gathered some of them here for you.
We could have represented all of these as hex values but as I've gotten them from different sources I've left them as found.
Last modified 1yr ago