embedded_redis_client/embedded_redis_server/
util.rs1use std::process::Command;
2
3fn kill_process_occupying_target_tcp_port(port: u16) {
5 let target_port = format!("TCP:{}", port);
6
7 let process_using_target_port = Command::new("lsof")
9 .args(&["-t", "-i", &target_port])
10 .output()
11 .expect("Failed to identify other processes using target TCP port");
12 if cfg!(debug_assertions) {
13 println!("Process using target port {:?}", process_using_target_port);
14 }
15
16 let mut process_using_target_port =
17 String::from_utf8(process_using_target_port.stdout).unwrap();
18 trim_newline(&mut process_using_target_port);
19 if cfg!(debug_assertions) {
20 println!("Kill arg {:?}", process_using_target_port);
21 }
22
23 let output = Command::new("kill")
24 .arg(process_using_target_port)
25 .output()
26 .expect("Failed to terminate other processes using target TCP port");
27 if cfg!(debug_assertions) {
28 println!("Killed process using target TCP port: {:?}", output);
29 }
30}
31
32pub fn get_processes_using_target_port(port: u16) -> Vec<u16> {
33 let target_port = format!("TCP:{}", port);
34
35 let process_using_target_port = Command::new("lsof")
37 .args(&["-t", "-i", &target_port])
38 .output()
39 .expect(format!("Failed to determine if local port {} is in use.", port).as_str());
40 if cfg!(debug_assertions) {
41 println!("Process using target port {:?}", process_using_target_port);
42 }
43 let process_using_target_port = String::from_utf8(process_using_target_port.stdout).unwrap();
44
45 let process_using_target_port: Vec<u16> = process_using_target_port
46 .split_whitespace()
47 .map(|s| {
48 s.parse()
49 .expect(format!("Unable to parse {} into a u16", s).as_str())
50 })
51 .collect();
52 return process_using_target_port;
53}
54
55fn trim_newline(s: &mut String) {
56 if s.ends_with('\n') {
57 s.pop();
58 if s.ends_with('\r') {
59 s.pop();
60 }
61 }
62}