The UnixListener::accept() method in Rust blocks by default because it waits for an incoming connection. Here are several ways to handle this:
1. Use Non-blocking Mode
Set the listener to non-blocking mode so accept() returns immediately:
use std::os::unix::net::UnixListener;
use std::io::ErrorKind;
let listener = UnixListener::bind("/tmp/socket")?;
listener.set_nonblocking(true)?;
loop {
match listener.accept() {
Ok((stream, _addr)) => {
// Handle connection
}
Err(e) if e.kind() == ErrorKind::WouldBlock => {
// No connection available, do other work
std::thread::sleep(std::time::Duration::from_millis(10));
}
Err(e) => {
// Handle actual error
eprintln!("Accept error: {}", e);
}
}
}
2. Use Async with Tokio
Tokio provides async Unix sockets that don't block the thread:
use tokio::net::UnixListener;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
let listener = UnixListener::bind("/tmp/socket")?;
loop {
let (stream, _) = listener.accept().await?;
// Spawn a task to handle the connection
tokio::spawn(async move {
// Handle stream
});
}
}
3. Use a Separate Thread
Keep the blocking behavior but run it in a dedicated thread:
use std::os::unix::net::UnixListener;
use std::thread;
use std::sync::mpsc;
let (tx, rx) = mpsc::channel();
thread::spawn(move || {
let listener = UnixListener::bind("/tmp/socket").unwrap();
loop {
match listener.accept() {
Ok((stream, _)) => {
tx.send(stream).unwrap();
}
Err(e) => eprintln!("Accept error: {}", e),
}
}
});
// Main thread can do other work and check for connections
loop {
match rx.try_recv() {
Ok(stream) => {
// Handle new connection
}
Err(mpsc::TryRecvError::Empty) => {
// Do other work
}
Err(mpsc::TryRecvError::Disconnected) => break,
}
}
4. Use mio for Event-Driven I/O
The mio crate provides low-level event-driven I/O:
use mio::{Events, Interest, Poll, Token};
use mio::net::UnixListener;
const SERVER: Token = Token(0);
let mut poll = Poll::new()?;
let mut events = Events::with_capacity(128);
let listener = UnixListener::bind("/tmp/socket")?;
poll.registry().register(
&mut listener,
SERVER,
Interest::READABLE
)?;
loop {
poll.poll(&mut events, None)?;
for event in events.iter() {
match event.token() {
SERVER => {
// Accept connection when ready
match listener.accept() {
Ok((stream, _)) => {
// Handle connection
}
Err(e) => eprintln!("Accept error: {}", e),
}
}
_ => unreachable!(),
}
}
}
The best approach depends on your application's architecture. For most cases, using Tokio's async runtime is the simplest and most efficient solution.