epoll.rs |
Linux `epoll` support.
# Examples
```no_run
# #[cfg(feature = "net")]
# fn main() -> std::io::Result<()> {
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)?;
}
}
}
# }
# #[cfg(not(feature = "net"))]
# fn main() {}
``` |
13644 |
mod.rs |
|
86 |
poll_fd.rs |
|
2985 |
syscalls.rs |
linux_raw syscalls supporting `rustix::event`.
# Safety
See the `rustix::backend` module documentation for details. |
3985 |
types.rs |
|
657 |