Skip to content

Instantly share code, notes, and snippets.

@xbee
Created August 3, 2019 04:47
Show Gist options
  • Save xbee/ac955ba0011d66a991ac2e047a46df90 to your computer and use it in GitHub Desktop.
Save xbee/ac955ba0011d66a991ac2e047a46df90 to your computer and use it in GitHub Desktop.
Rust single instance process #rust #single instance
use std::net::TcpListener;
fn create_app_lock(port: u16) -> TcpListener {
match TcpListener::bind(("0.0.0.0", port)) {
Ok(socket) => {
socket
},
Err(_) => {
panic!("Couldn't lock port {}: another instance already running?", port);
}
}
}
fn remove_app_lock(socket: TcpListener) {
drop(socket);
}
fn main() {
let lock_socket = create_app_lock(12345);
// ...
// your code here
// ...
remove_app_lock(lock_socket);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment