Skip to content

Instantly share code, notes, and snippets.

@kavanmevada
Created August 25, 2021 13:42
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kavanmevada/a17ede820bfc146e48693f22bb6bfc0e to your computer and use it in GitHub Desktop.
Save kavanmevada/a17ede820bfc146e48693f22bb6bfc0e to your computer and use it in GitHub Desktop.
use std::ptr::addr_of_mut;
static mut EVENTS: [libc::epoll_event; 10] = [libc::epoll_event { events: 0, u64: 0 }; 10];
pub fn main() {
let tv = std::time::Instant::now();
unsafe {
let efd = libc::eventfd(0, libc::EFD_NONBLOCK);
std::thread::spawn(move || {
for _ in 0..5 {
libc::write(efd, &mut 4u64 as *mut _ as _, 8);
libc::sleep(1 as u32);
}
});
let ep_fd = libc::epoll_create1(0);
let mut read_event = libc::epoll_event {
events: (libc::EPOLLHUP | libc::EPOLLERR | libc::EPOLLIN) as u32,
u64: efd as u64,
};
libc::epoll_ctl(ep_fd, libc::EPOLL_CTL_ADD, efd, addr_of_mut!(read_event));
loop {
match libc::epoll_wait(ep_fd, addr_of_mut!(EVENTS) as _, 10, 5000) {
0 => break,
ret => {
for i in 0..ret as usize {
if EVENTS[i as usize].events & libc::EPOLLIN as u32 != 0 {
let mut count = 0;
let event_fd = EVENTS[i as usize].u64 as i32;
if libc::read(event_fd, addr_of_mut!(count) as _, 8) < 0 {
panic!("read fail");
}
println!(
"success read from efd, read {} bytes({}) at {}",
ret,
count,
tv.elapsed().as_secs()
);
}
}
}
}
}
libc::close(ep_fd);
libc::close(efd);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment