eventfd_read - Linux


Overview

eventfd_read reads an eventfd file descriptor, returning the count of events that have not yet been read. Eventfd files can be used to implement non-blocking synchronization mechanisms.

Syntax

#include <sys/eventfd.h>

ssize_t eventfd_read(int fd, eventfd_t *value);

Options/Flags

None.

Examples

Simple Example:

#include <sys/eventfd.h>
#include <stdio.h>

int main() {
    int fd = eventfd(0, EFD_CLOEXEC);
    if (fd == -1) {
        perror("eventfd");
        return 1;
    }

    eventfd_t value;
    if (eventfd_read(fd, &value) == -1) {
        perror("eventfd_read");
        return 1;
    }

    printf("Value: %llu\n", value);
    return 0;
}

Advanced Example:

#include <sys/eventfd.h>
#include <sys/epoll.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main() {
    int efd = eventfd(0, EFD_CLOEXEC);
    if (efd == -1) {
        perror("eventfd");
        return 1;
    }

    int epfd = epoll_create1(0);
    if (epfd == -1) {
        perror("epoll_create1");
        return 1;
    }

    struct epoll_event event;
    event.events = EPOLLIN;
    event.data.fd = efd;
    if (epoll_ctl(epfd, EPOLL_CTL_ADD, efd, &event) == -1) {
        perror("epoll_ctl");
        return 1;
    }

    while (1) {
        struct epoll_event events[1];
        int nfds = epoll_wait(epfd, events, 1, -1);
        if (nfds == -1) {
            perror("epoll_wait");
            return 1;
        }

        eventfd_t value;
        if (eventfd_read(efd, &value) == -1) {
            perror("eventfd_read");
            return 1;
        }

        printf("Event: %llu\n", value);
    }

    close(efd);
    close(epfd);
    return 0;
}

Common Issues

  • Ensure that the eventfd file descriptor is valid and has been opened for reading.
  • The value returned by eventfd_read is 0 if no events have occurred since the last read. This is not an error condition.
  • Use eventfd_write to send events to the eventfd file descriptor.

Integration

Eventfd files can be used with epoll to create non-blocking synchronization mechanisms. For example, one thread can wait on an eventfd file descriptor while another thread signals the event using eventfd_write.

Related Commands

  • eventfd
  • eventfd_write