use std::process::Command;
fn kill_process_occupying_target_tcp_port(port: u16) {
let target_port = format!("TCP:{}", port);
let process_using_target_port = Command::new("lsof")
.args(&["-t", "-i", &target_port])
.output()
.expect("Failed to identify other processes using target TCP port");
if cfg!(debug_assertions) {
println!("Process using target port {:?}", process_using_target_port);
}
let mut process_using_target_port =
String::from_utf8(process_using_target_port.stdout).unwrap();
trim_newline(&mut process_using_target_port);
if cfg!(debug_assertions) {
println!("Kill arg {:?}", process_using_target_port);
}
let output = Command::new("kill")
.arg(process_using_target_port)
.output()
.expect("Failed to terminate other processes using target TCP port");
if cfg!(debug_assertions) {
println!("Killed process using target TCP port: {:?}", output);
}
}
pub fn get_processes_using_target_port(port: u16) -> Vec<u16> {
let target_port = format!("TCP:{}", port);
let process_using_target_port = Command::new("lsof")
.args(&["-t", "-i", &target_port])
.output()
.expect(format!("Failed to determine if local port {} is in use.", port).as_str());
if cfg!(debug_assertions) {
println!("Process using target port {:?}", process_using_target_port);
}
let process_using_target_port = String::from_utf8(process_using_target_port.stdout).unwrap();
let process_using_target_port: Vec<u16> = process_using_target_port
.split_whitespace()
.map(|s| {
s.parse()
.expect(format!("Unable to parse {} into a u16", s).as_str())
})
.collect();
return process_using_target_port;
}
fn trim_newline(s: &mut String) {
if s.ends_with('\n') {
s.pop();
if s.ends_with('\r') {
s.pop();
}
}
}