Skip to content

Instantly share code, notes, and snippets.

@ugovaretto
Created June 6, 2022 10:17
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 ugovaretto/e3648c92229e97395287b0ec119865be to your computer and use it in GitHub Desktop.
Save ugovaretto/e3648c92229e97395287b0ec119865be to your computer and use it in GitHub Desktop.
Async file I/O with aio* functions
// Async file I/O
use libc::{aio_read, aiocb, aio_error, aio_return};
use std::fs::File;
use std::os::unix::io::AsRawFd;
fn main() {
let file = File::open("src/main.rs").unwrap();
let mut buf = [0; 1024];
let mut cb = aiocb {
aio_fildes: file.as_raw_fd(),
aio_buf: buf.as_mut_ptr() as *mut libc::c_void,
aio_nbytes: buf.len() as libc::size_t,
aio_offset: 0,
aio_reqprio: 0,
aio_lio_opcode: 0,
aio_sigevent: unsafe{::std::mem::zeroed()},
};
unsafe {
if aio_read(&mut cb) < 0 { panic!("aio_read failed"); }
while aio_error(&cb) == libc::EINPROGRESS {
println!("waiting for read to complete");
}
let read = aio_return(&mut cb);
if read < 0 { panic!("aio_return failed"); }
println!("read {} bytes", read);
}
println!("{}", String::from_utf8_lossy(buf.as_ref()));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment