To understand Mio, I wrote a small example:
I use mkfifo p
to make a named pipe, and in one of the terminal windows, I use:
cat > p
to send content to the pipe
In the code,
- I opened the file,
- add the file
fd
to theepoll's
interest list. - epoll_wait to wait for events
I can correctly get the readable event:
Event { token: Token(1), readable: true, writable: false, error: false, read_closed: false, write_closed: false, priority: false, aio: false, lio: false }
However, when I tried to file::read_into_string
, the process hung.
I tried to trace the code and it uses libc
to read the file. As I'm fairly new to Rust, I can't get useful errors from the result.
Any suggestions? Thanks in advance.
use std::error::Error;
use std::io::Read;
use std::os::unix::io::AsRawFd;
use mio::net::{TcpListener, TcpStream};
use mio::{Events, Interest, Poll, Token};
// Some tokens to allow us to identify which event is for which socket.
const SERVER: Token = Token(0);
const File: Token = Token(1);
// fn main() -> Result<(), Box<dyn Error>> {
fn main() {
let mut file = std::env::args().nth(1).unwrap();
let mut top_poll = Poll::new().unwrap();
use std::fs::File;
let mut f = File::open(file).unwrap();
use mio::unix::SourceFd;
use std::os::unix::io::AsRawFd;
top_poll.registry().register(&mut SourceFd(&f.as_raw_fd()), File, Interest::READABLE);
let mut top_events = Events::with_capacity(128);
loop {
// top epoll
top_poll.poll(&mut top_events, None).unwrap();
let mut cont = String::new();
for e in top_events.iter() {
println!("{:?}", e);
println!("start to read file");
let flen = f.read_to_string(&mut cont).unwrap();
println!("{:?}, content {}", flen, cont);
}
}
}