🐛 修复退出程序后 aria2 依然在后台
This commit is contained in:
@@ -1,3 +1,6 @@
|
||||
use utils::download_manager::DownloadManager;
|
||||
use tauri::Manager;
|
||||
|
||||
mod models;
|
||||
mod handlers;
|
||||
mod utils;
|
||||
@@ -29,6 +32,14 @@ pub fn run() {
|
||||
handlers::download::cancel_download,
|
||||
utils::get_user_agent,
|
||||
])
|
||||
.on_window_event(|window, event| match event {
|
||||
tauri::WindowEvent::Destroyed => {
|
||||
// 获取 DownloadManager 实例并关闭 aria2
|
||||
let download_manager = window.state::<DownloadManager>();
|
||||
download_manager.shutdown_aria2();
|
||||
}
|
||||
_ => {}
|
||||
})
|
||||
.run(tauri::generate_context!())
|
||||
.expect("error while running tauri application");
|
||||
}
|
||||
|
||||
@@ -14,6 +14,7 @@ pub struct DownloadManager {
|
||||
queue: Mutex<HashMap<String, DownloadTask>>,
|
||||
aria2_started: Arc<AtomicBool>,
|
||||
aria2_port: Arc<Mutex<u16>>,
|
||||
aria2_pid: Arc<Mutex<Option<u32>>>,
|
||||
}
|
||||
|
||||
impl DownloadManager {
|
||||
@@ -22,6 +23,7 @@ impl DownloadManager {
|
||||
queue: Mutex::new(HashMap::new()),
|
||||
aria2_started: Arc::new(AtomicBool::new(false)),
|
||||
aria2_port: Arc::new(Mutex::new(5144)),
|
||||
aria2_pid: Arc::new(Mutex::new(None)),
|
||||
}
|
||||
}
|
||||
|
||||
@@ -172,7 +174,7 @@ impl DownloadManager {
|
||||
}
|
||||
|
||||
// 启动 aria2c
|
||||
Command::new("aria2c")
|
||||
let child = Command::new("aria2c")
|
||||
.args([
|
||||
"--enable-rpc",
|
||||
"--rpc-listen-all=false",
|
||||
@@ -182,6 +184,11 @@ impl DownloadManager {
|
||||
.spawn()
|
||||
.map_err(|e| format!("启动 aria2 失败: {}", e)).unwrap();
|
||||
|
||||
// 保存进程 ID
|
||||
if let Ok(mut pid_guard) = self.aria2_pid.lock() {
|
||||
*pid_guard = Some(child.id());
|
||||
}
|
||||
|
||||
self.aria2_started.store(true, Ordering::SeqCst);
|
||||
}
|
||||
|
||||
@@ -346,4 +353,26 @@ impl DownloadManager {
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// 关闭 aria2
|
||||
pub fn shutdown_aria2(&self) {
|
||||
if self.aria2_started.load(Ordering::SeqCst) {
|
||||
// 获取保存的 PID
|
||||
if let Ok(pid_guard) = self.aria2_pid.lock() {
|
||||
if let Some(pid) = *pid_guard {
|
||||
// 使用 kill 命令终止特定的进程
|
||||
if let Ok(output) = Command::new("kill")
|
||||
.arg(pid.to_string())
|
||||
.output() {
|
||||
if output.status.success() {
|
||||
println!("成功关闭 aria2 (PID: {})", pid);
|
||||
} else {
|
||||
eprintln!("关闭 aria2 失败 (PID: {})", pid);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
self.aria2_started.store(false, Ordering::SeqCst);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user