I used async_std::fs::File
to create a tun device:
async fn new_tun() -> File {
let file = OpenOptions::new()
.read(true)
.write(true)
.open("/dev/net/tun")
.await?;
// ifreq is generated using bindgen and a wrapper around `if.h` header file
let req = ifreq::new((IFF_TUN | IFF_NO_PI) as _).unwrap();
// tunsetiff is generated using `ioctl_write_int!(tunsetiff, b'T', 202)`
let ioctl_ret = unsafe { tunsetiff(file.as_raw_fd(), &req as *const ifreq as u64) }.unwrap();
// ip commands to up device
file
}
However, reading from tun file always returns zero bytes without waiting for incoming data events:
pub async fn read(&mut self, buf: &mut [u8]) {
let mut buf = vec![0u8; 1024];
loop {
// Issue: always is Ready and returns immediately with zero bytes
let n = self.file.read(&mut buf).await.unwrap();
if n > 0 {
// ...
} else if n == 0 {
// Always n is zero!
}
buf.clear();
}
}
The loop causes a 100% CPU usage. Any idea to fix the issue?