Check out my first novel, midnight's simulacra!

Eventfd

From dankwiki
Revision as of 18:08, 22 May 2023 by Dank (talk | contribs)

Linux offers the eventfd abstraction for file descriptor-based userspace notification. It is backed by a single uint64_t in the kernel, unlike a pipe (which is usually backed by a much larger buffer). It is thus the most lightweight method of IPC available to userspace. The maximum value of the eventfd counter is 2^64-2 (0xfffffffffffffffe), and the minimum (and default) value is 0.

In the past, a full pipe was often used to interrupt a thread that was blocking in poll(2) (or select, or epoll, etc.). An eventfd can serve this same purpose while requiring less kernel memory.

write(2)s add the submitted eight-byte value to the value currently in the eventfd, unless they would cause the counter to exceed its maximum value, in which case they block. read(2)s return this eight-byte value, unless it is zero, in which case they block until the counter becomes non-zero. Following a successful read(2), the counter is reset to zero (if EFD_SEMAPHORE was not specified) or decremented by one (if EFD_SEMAPHORE was specified).

POLLOUT is high whenever the value of the eventfd is less than its maximum, i.e. 0xfffffffffffffffd or less. It only guarantees that a value of 1 can be written without blocking.