Info
This post is auto-generated from RSS feed The Rust Programming Language Forum - Latest topics. Source: How to read a UnixStream
Hello, I am trying to make a background daemon process that receives commands from bash and calls a function depending on the command. Using the tokio library.
The script simply connects to a unix socket and should receive commands from another script handling the cli. I want it to work like lxd or docker where you input commands and it executes a function.
The thing is, I just don't know how to process a UnixStream from the tokio library. I've tried reading the documentation but none of it really points to any examples of reading bash commands.
Here is the basic code that doesn't do much so far. As you can see, I'm quite clueless on how the UnixStream works.
#[tokio::main]
async fn main(){
println!("Running command listener...");
let socket_path = "/tmp/test_socket.sock";
let _ = std::fs::remove_file(socket_path); // Clean previous runs
// Bind to Unix socket
let listener = UnixListener::bind(socket_path).unwrap();
println!("Daemon listening on {}", socket_path);
// Main server loop
while let Ok((mut stream, _addr)) = listener.accept().await{
println!("Got a client");
// Handle each new client connection
tokio::spawn(async move{
// Try to read the stream here
stream.writable().await.unwrap();
stream.write_all(b"hello world").await.unwrap();
stream.readable().await.unwrap();
let mut response = String::new();
stream.read_to_string(&mut response).await.unwrap();
println!("{}", response);
});
}
}
If you could provide any examples of reading bash commands from the Unix Stream, then it would be greatly appreciated.
2 posts - 2 participants
🏷️ Rust_feed