Handle previous sockets in Listener::new()

This commit is contained in:
Iris Pupo 2022-12-04 01:08:36 -05:00
parent 01e2aee164
commit 0768a7dc61
1 changed files with 19 additions and 1 deletions

View File

@ -17,6 +17,8 @@ use slab::Slab;
use crate::protocol::*;
use crate::service::window::{WindowMessage, WindowMessageSender};
use std::io::{Error, ErrorKind};
const SOCK_NAME: &str = "magpie.sock";
#[derive(Debug)]
@ -71,8 +73,24 @@ impl Listener {
let sock_dir = std::env::var("XDG_RUNTIME_DIR").expect("XDG_RUNTIME_DIR not set");
let sock_dir = Path::new(&sock_dir);
let sock_path = sock_dir.join(SOCK_NAME);
eprintln!("Making socket at: {:?}", sock_path);
match UnixStream::connect(&sock_path) {
Ok(_) => {
eprintln!("Socket is already in use. Another instance of Magpie may be running.");
let kind = ErrorKind::AddrInUse;
let error = Error::new(kind, "Socket is already in use.");
return Err(error);
}
Err(ref err) if err.kind() == ErrorKind::ConnectionRefused => {
eprintln!("Found leftover socket; removing");
std::fs::remove_file(&sock_path)?;
}
Err(ref err) if err.kind() == ErrorKind::NotFound => {}
Err(err) => return Err(err)
}
eprintln!("Making socket at: {:?}", sock_path);
let uds = UnixListener::bind(&sock_path)?;
let path = sock_path.to_path_buf();
Ok(Self{uds, path})