1use std::process::Command;
2
3pub struct Killer {
4 pub port: u32,
5}
6
7impl Killer {
8 pub fn kill_process_by_port(&self) {
9 if let Some(pid) = get_pid_by_port(&self.port) {
10 println!(
11 "PID of the process listening on port {}: {}",
12 self.port, pid
13 );
14 kill_process(pid);
15 } else {
16 println!("No process found listening on port {}", self.port);
17 }
18 }
19}
20
21pub fn get_pid_by_port(port: &u32) -> Option<u32> {
22 println!("port: {}", port);
23 let lsof_output = Command::new("lsof")
24 .arg("-t")
25 .arg("-i")
26 .arg(format!(":{}", port))
27 .output()
28 .expect("No pid found");
29
30 println!("{:#?}", lsof_output);
31
32 if lsof_output.stdout.is_empty() {
33 return None;
34 }
35
36 let output_str = String::from_utf8_lossy(&lsof_output.stdout);
37 let lines: Vec<&str> = output_str.split('\n').collect();
38
39 Some(lines[0].parse::<u32>().unwrap())
40}
41
42pub fn kill_process(pid: u32) {
43 Command::new("kill")
44 .arg("-9")
45 .arg(format!("{}", pid))
46 .output()
47 .expect("Cannot kill process");
48}