feat: kill clash by pid

This commit is contained in:
GyDi
2022-09-05 16:30:29 +08:00
committed by GitHub
parent 7f0a04e3e3
commit 000d6ebcd0
5 changed files with 109 additions and 2 deletions

View File

@@ -53,6 +53,9 @@ impl Core {
/// initialize the core state
pub fn init(&self, app_handle: tauri::AppHandle) {
// kill old clash process
Service::kill_old_clash();
let verge = self.verge.lock();
let clash_core = verge.clash_core.clone();

View File

@@ -4,6 +4,8 @@ use crate::utils::{config, dirs};
use anyhow::{bail, Result};
use reqwest::header::HeaderMap;
use serde_yaml::Mapping;
use std::fs;
use std::io::Write;
use std::{collections::HashMap, time::Duration};
use tauri::api::process::{Command, CommandChild, CommandEvent};
use tokio::time::sleep;
@@ -99,6 +101,14 @@ impl Service {
let cmd = Command::new_sidecar(clash_core)?;
let (mut rx, cmd_child) = cmd.args(["-d", app_dir]).spawn()?;
// 将pid写入文件中
let pid = cmd_child.pid();
log_if_err!(|| -> Result<()> {
let path = dirs::clash_pid_path();
fs::File::create(path)?.write(format!("{pid}").as_bytes())?;
Ok(())
}());
self.sidecar = Some(cmd_child);
// clash log
@@ -217,6 +227,23 @@ impl Service {
Ok((server, headers))
}
/// kill old clash process
pub fn kill_old_clash() {
use sysinfo::{Pid, PidExt, ProcessExt, System, SystemExt};
if let Ok(pid) = fs::read(dirs::clash_pid_path()) {
if let Ok(pid) = String::from_utf8_lossy(&pid).parse() {
let mut system = System::new();
system.refresh_all();
let proc = system.process(Pid::from_u32(pid));
if let Some(proc) = proc {
proc.kill();
}
}
}
}
}
impl Drop for Service {

View File

@@ -15,7 +15,6 @@ static VERGE_CONFIG: &str = "verge.yaml";
static PROFILE_YAML: &str = "profiles.yaml";
static PROFILE_TEMP: &str = "clash-verge-runtime.yaml";
#[cfg(windows)]
static mut RESOURCE_DIR: Option<PathBuf> = None;
/// portable flag
@@ -65,7 +64,6 @@ pub fn app_resources_dir(package_info: &PackageInfo) -> PathBuf {
.unwrap()
.join("resources");
#[cfg(windows)]
unsafe {
RESOURCE_DIR = Some(res_dir.clone());
}
@@ -103,6 +101,10 @@ pub fn profiles_temp_path() -> PathBuf {
return app_home_dir().join(PROFILE_TEMP);
}
pub fn clash_pid_path() -> PathBuf {
unsafe { RESOURCE_DIR.clone().unwrap().join("clash.pid") }
}
#[cfg(windows)]
static SERVICE_PATH: &str = "clash-verge-service.exe";