Skip to main content

Mountain/IPC/WindServiceHandlers/Terminal/
LocalPTYFreePortKillProcess.rs

1//! Wire method: `localPty:freePortKillProcess`.
2//! Kills whatever process is holding a TCP port so a new terminal can bind it.
3//! On Unix, uses `lsof -t -i :<port>` to list PIDs then `kill -9` each one.
4//! No-op on unknown port (0) or non-Unix platforms.
5
6use serde_json::{Value, json};
7
8use crate::IPC::WindServiceHandlers::Utilities::JsonValueHelpers::arg_u64;
9
10pub async fn Fn(Arguments:Vec<Value>) -> Result<Value, String> {
11	let Port = arg_u64(&Arguments, 0) as u16;
12
13	if Port > 0 {
14		#[cfg(unix)]
15		{
16			let Out = tokio::process::Command::new("lsof")
17				.args(["-t", "-i", &format!(":{}", Port)])
18				.output()
19				.await;
20
21			if let Ok(O) = Out {
22				let Pids = String::from_utf8_lossy(&O.stdout);
23
24				for Pid in Pids.split_whitespace() {
25					if let Ok(P) = Pid.parse::<u32>() {
26						let _ = tokio::process::Command::new("kill").args(["-9", &P.to_string()]).status().await;
27					}
28				}
29			}
30		}
31	}
32
33	Ok(Value::Null)
34}