Module rustix::event::epoll

source ·
Expand description

Linux epoll support.

Examples

use rustix::event::epoll;
use rustix::fd::AsFd;
use rustix::io::{ioctl_fionbio, read, write};
use rustix::net::{
    accept, bind_v4, listen, socket, AddressFamily, Ipv4Addr, SocketAddrV4, SocketType,
};
use std::collections::HashMap;
use std::os::unix::io::AsRawFd;

// Create a socket and listen on it.
let listen_sock = socket(AddressFamily::INET, SocketType::STREAM, None)?;
bind_v4(&listen_sock, &SocketAddrV4::new(Ipv4Addr::LOCALHOST, 0))?;
listen(&listen_sock, 1)?;

// Create an epoll object. Using `Owning` here means the epoll object will
// take ownership of the file descriptors registered with it.
let epoll = epoll::create(epoll::CreateFlags::CLOEXEC)?;

// Register the socket with the epoll object.
epoll::add(
    &epoll,
    &listen_sock,
    epoll::EventData::new_u64(1),
    epoll::EventFlags::IN,
)?;

// Keep track of the sockets we've opened.
let mut next_id = epoll::EventData::new_u64(2);
let mut sockets = HashMap::new();

// Process events.
let mut event_list = epoll::EventVec::with_capacity(4);
loop {
    epoll::wait(&epoll, &mut event_list, -1)?;
    for event in &event_list {
        let target = event.data;
        if target.u64() == 1 {
            // Accept a new connection, set it to non-blocking, and
            // register to be notified when it's ready to write to.
            let conn_sock = accept(&listen_sock)?;
            ioctl_fionbio(&conn_sock, true)?;
            epoll::add(
                &epoll,
                &conn_sock,
                next_id,
                epoll::EventFlags::OUT | epoll::EventFlags::ET,
            )?;

            // Keep track of the socket.
            sockets.insert(next_id, conn_sock);
            next_id = epoll::EventData::new_u64(next_id.u64() + 1);
        } else {
            // Write a message to the stream and then unregister it.
            let target = sockets.remove(&target).unwrap();
            write(&target, b"hello\n")?;
            let _ = epoll::delete(&epoll, &target)?;
        }
    }
}

Structs

  • EPOLL_* for use with [new].
  • A record of an event that occurred.
  • EPOLL* for use with add.
  • A vector of Events, plus context for interpreting them.
  • An iterator over the Events in an EventVec.

Functions

  • epoll_ctl(self, EPOLL_CTL_ADD, data, event)—Adds an element to an epoll object.
  • epoll_create1(flags)—Creates a new epoll object.
  • epoll_ctl(self, EPOLL_CTL_DEL, target, NULL)—Removes an element in a given epoll object.
  • epoll_ctl(self, EPOLL_CTL_MOD, target, event)—Modifies an element in a given epoll object.
  • epoll_wait(self, events, timeout)—Waits for registered events of interest.

Unions

  • Data associated with an Event. This can either be a 64-bit integer value or a pointer which preserves pointer provenance.