Skip to main content

Mountain/IPC/WindServiceHandlers/Terminal/
LocalPTYFreePortKillProcess.rs

1#![allow(unused_variables, dead_code, unused_imports)]
2
3//! Wire method: `localPty:freePortKillProcess`.
4//! Kills whatever process is holding a TCP port so a new terminal can bind it.
5//! On Unix, uses `lsof -t -i :<port>` to list PIDs then `kill -9` each one.
6//! No-op on unknown port (0) or non-Unix platforms.
7
8use serde_json::{Value, json};
9
10pub async fn Fn(Arguments:Vec<Value>) -> Result<Value, String> {
11	let Port = Arguments.first().and_then(|V| V.as_u64()).unwrap_or(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}