I actually want to catch a specific OSError, an OSError with errorCode
EADDRINUSE. I want to port this to Nim:
[https://gitlab.com/snippets/1903637](https://gitlab.com/snippets/1903637)
Note how I caught the specific exception, otherwise I raise exception again:
auto sock = new Socket(AddressFamily.UNIX, SocketType.DGRAM);
auto addr = new UnixAddress("\0com.gitlab.events.app.sock");
const bool isPrimary = () {
try {
sock.bind(addr);
}
catch (SocketOSException e) {
import core.stdc.errno : EADDRINUSE;
if (e.errorCode == EADDRINUSE) {
log("Duplicate instance detected.");
return false;
}
else {
throw e;
}
}
log("Primary instance detected.");
return true;
}();
Run
let sock: RawFd = socket(
AddressFamily::Unix,
SockType::Datagram,
SockFlag::empty(),
None, // Protocol
)?;
let addr =
SockAddr::Unix(UnixAddr::new_abstract(SOCK_ADDR.as_bytes())?);
match bind(sock, &addr) {
Err(e) => match e {
Sys(EADDRINUSE) => {
println!("Secondary instance detected, launching client.");
if client(sock, &addr).is_ok() {
println!("Message sent.");
}
}
_ => {
panic!("Socket binding failed due to: {:?}", e);
}
},
Ok(_) => {
println!("Primary instance detected, launching server.");
server(sock)?;
}
}
Run