Reputation: 113
I am writing a small application in Rust that runs a loop every 250ms.
I want the application to check a UnixDatagram every time the loop runs to see if there are new messages passed into the Datagram. (the messages adjust control settings for another peripheral, details aren't relevant here). My desired behavior is that most of the time, the loop will check the Datagram for new messages, find none, do nothing, and continue with other loop logic. If there is a message in the datagram, parse the message, update settings, then continue other loop logic.
Here's the simplified Rust code I'm working on:
let socket_path = "/home/trig/socketdir/trig_led_socket";
let sock = match UnixDatagram::bind(socket_path) {
Ok(sock) => sock,
Err(e) => panic!("Couldn't bind at {}: {:?}", socket_path, e),
};
sock.send_to(b"hello world", socket_path);
... (about 20 seconds later)
let mut buf = [0; 100];
let (count, address) = sock.recv_from(&mut buf)?;
println!("socket {:?} sent {:?}", address, &buf[..count]);
So far, this all works as I would expect. My "hello world" message is read from the datagram 20 seconds later, and printed out to the console. My troubles show up if I try to call the "recv_from" function more than once.
After the first successful read, the program hangs at the "recv_from" line. I believe this is due to the UnixDatagram's default read_timeout being 'none'. I verified this by trying the read_timeout command and printing the results.
I tried setting the socket to nonblocking mode using the set_nonblocking command. Now, instead of hanging, I get an error when the second recv_from command runs: Error: Os { code: 11, kind: WouldBlock, message: "Resource temporarily unavailable" }
All I want to do is ignore this WouldBlock error, continue my logic, and try again on the next loop. How do I properly handle this WouldBlock error?
Upvotes: 0
Views: 102