Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
17 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions .changes/cli-dev-kill-process-tree.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
---
"tauri-cli": patch:bug
"@tauri-apps/cli": patch:bug
---

`tauri dev` now kills the whole process tree of the running app when it restarts or exits, so processes spawned by the app (e.g. sidecars) are no longer left orphaned.
5 changes: 5 additions & 0 deletions .changes/plugin-cleanup-before-exit.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"tauri": minor:feat
---

Added the `Plugin::cleanup_before_exit` hook and `plugin::Builder::on_cleanup_before_exit`, invoked by `App::cleanup_before_exit` right before the process exits so plugins can release resources such as sidecar processes. Unlike `RunEvent::Exit`, it also runs on exit paths that bypass the event loop such as `AppHandle::restart` on the main thread.
36 changes: 36 additions & 0 deletions crates/tauri-cli/src/interface/rust/desktop.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,42 @@ pub struct DevChild {

impl DevProcess for DevChild {
fn kill(&self) -> std::io::Result<()> {
let pid = self.dev_child.id();

#[cfg(windows)]
{
// `/T` terminates the whole process tree, `/F` forces it
let pid = pid.to_string();
let _ = Command::new("taskkill")
.args(["/T", "/F", "/PID", pid.as_str()])
.status();
}

#[cfg(not(windows))]
{
// collect the whole tree first, then kill the root before its descendants
// so it cannot respawn them in the meantime
const KILL_TREE: &str = r#"
descendants() {
for child in $(pgrep -P "$1" 2>/dev/null); do
echo "$child"
descendants "$child"
done
}
tree=$(descendants "$1")
kill -9 "$1" 2>/dev/null
for p in $tree; do
kill -9 "$p" 2>/dev/null
done
true
"#;

let pid = pid.to_string();
let _ = Command::new("sh")
.args(["-c", KILL_TREE, "sh", pid.as_str()])
.status();
}
Comment thread
Legend-Master marked this conversation as resolved.
Resolved

self.dev_child.kill()?;
self.manually_killed_app.store(true, Ordering::SeqCst);
Ok(())
Expand Down
9 changes: 9 additions & 0 deletions crates/tauri/src/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1108,6 +1108,15 @@ macro_rules! shared_app_impl {
/// Runs necessary cleanup tasks before exiting the process.
/// **You should always exit the tauri app immediately after this function returns and not use any tauri-related APIs.**
pub fn cleanup_before_exit(&self) {
// run plugin cleanup hooks first so plugins can still use the app resources (e.g. stop sidecars)
// cleanup is best-effort, so a plugin store poisoned by an earlier panic must not abort it
self
.manager
.plugins
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.cleanup_before_exit(self.app_handle());

#[cfg(all(desktop, feature = "tray-icon"))]
self.manager.tray.icons.lock().unwrap().clear();
self.manager.resources_table().clear();
Expand Down
89 changes: 89 additions & 0 deletions crates/tauri/src/plugin.rs
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,22 @@ pub trait Plugin<R: Runtime>: Send {
#[allow(unused_variables)]
fn on_event(&mut self, app: &AppHandle<R>, event: &RunEvent) {}

/// Callback invoked by [`App::cleanup_before_exit`](crate::App::cleanup_before_exit) right before the process exits.
///
/// Use it to release resources the OS does not reclaim on its own, such as child processes (sidecars).
///
/// Unlike [`RunEvent::Exit`], this hook also runs on exit paths that bypass the event loop,
/// e.g. [`AppHandle::restart`] when called on the main thread. On a regular exit,
/// [`Plugin::on_event`] receives [`RunEvent::Exit`] first and then this hook is called.
/// It does **not** run when the process is killed (e.g. by `tauri dev` on rebuild)
/// or when `std::process::exit` is called directly.
///
/// The plugin store is locked while this hook runs, so it must not call APIs that access
/// other plugins such as [`AppHandle::remove_plugin`] or [`AppHandle::plugin`].
/// No Tauri API should be used after it returns.
#[allow(unused_variables)]
fn cleanup_before_exit(&mut self, app: &AppHandle<R>) {}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We would also want to implement this for the TauriPlugin so that tauri::plugin::Builder could have access to this API

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

for sure! I’ll add this to the TauriPlugin trait as well so it’s accessible via tauri::plugin::Builder.


// TODO: Change this to `run_invoke_handler` in v3
/// Extend commands to [`crate::Builder::invoke_handler`].
#[allow(unused_variables)]
Expand All @@ -117,6 +133,7 @@ type SetupHook<R, C> =
type OnWindowReady<R> = dyn FnMut(Window<R>) + Send;
type OnWebviewReady<R> = dyn FnMut(Webview<R>) + Send;
type OnEvent<R> = dyn FnMut(&AppHandle<R>, &RunEvent) + Send;
type OnCleanupBeforeExit<R> = dyn FnMut(&AppHandle<R>) + Send;
type OnNavigation<R> = dyn Fn(&Webview<R>, &Url) -> bool + Send;
type OnPageLoad<R> = dyn FnMut(&Webview<R>, &PageLoadPayload<'_>) + Send;
type OnDrop<R> = dyn FnOnce(AppHandle<R>) + Send;
Expand Down Expand Up @@ -272,6 +289,7 @@ pub struct Builder<R: Runtime, C: DeserializeOwned = ()> {
on_window_ready: Box<OnWindowReady<R>>,
on_webview_ready: Box<OnWebviewReady<R>>,
on_event: Box<OnEvent<R>>,
on_cleanup_before_exit: Box<OnCleanupBeforeExit<R>>,
on_drop: Option<Box<OnDrop<R>>>,
uri_scheme_protocols: HashMap<String, Arc<UriSchemeProtocol<R>>>,
}
Expand All @@ -289,6 +307,7 @@ impl<R: Runtime, C: DeserializeOwned> Builder<R, C> {
on_window_ready: Box::new(|_| ()),
on_webview_ready: Box::new(|_| ()),
on_event: Box::new(|_, _| ()),
on_cleanup_before_exit: Box::new(|_| ()),
on_drop: None,
uri_scheme_protocols: Default::default(),
}
Expand Down Expand Up @@ -568,6 +587,32 @@ impl<R: Runtime, C: DeserializeOwned> Builder<R, C> {
self
}

/// Callback invoked when the application is performing cleanup before exit.
///
/// See [`Plugin::cleanup_before_exit`] for details.
///
/// # Examples
///
/// ```rust
/// use tauri::{plugin::{Builder, TauriPlugin}, Runtime};
///
/// fn init<R: Runtime>() -> TauriPlugin<R> {
/// Builder::new("example")
/// .on_cleanup_before_exit(|app| {
/// // release OS resources such as child processes here
/// })
/// .build()
/// }
/// ```
#[must_use]
pub fn on_cleanup_before_exit<F>(mut self, on_cleanup_before_exit: F) -> Self
where
F: FnMut(&AppHandle<R>) + Send + 'static,
{
self.on_cleanup_before_exit = Box::new(on_cleanup_before_exit);
self
}

/// Callback invoked when the plugin is dropped.
///
/// # Examples
Expand Down Expand Up @@ -741,6 +786,7 @@ impl<R: Runtime, C: DeserializeOwned> Builder<R, C> {
on_window_ready: self.on_window_ready,
on_webview_ready: self.on_webview_ready,
on_event: self.on_event,
on_cleanup_before_exit: self.on_cleanup_before_exit,
on_drop: self.on_drop,
uri_scheme_protocols: self.uri_scheme_protocols,
})
Expand Down Expand Up @@ -768,6 +814,7 @@ pub struct TauriPlugin<R: Runtime, C: DeserializeOwned = ()> {
on_window_ready: Box<OnWindowReady<R>>,
on_webview_ready: Box<OnWebviewReady<R>>,
on_event: Box<OnEvent<R>>,
on_cleanup_before_exit: Box<OnCleanupBeforeExit<R>>,
on_drop: Option<Box<OnDrop<R>>>,
uri_scheme_protocols: HashMap<String, Arc<UriSchemeProtocol<R>>>,
}
Expand Down Expand Up @@ -848,6 +895,10 @@ impl<R: Runtime, C: DeserializeOwned> Plugin<R> for TauriPlugin<R, C> {
(self.on_event)(app, event)
}

fn cleanup_before_exit(&mut self, app: &AppHandle<R>) {
(self.on_cleanup_before_exit)(app)
}

fn extend_api(&mut self, invoke: Invoke<R>) -> bool {
(self.invoke_handler)(invoke)
}
Expand Down Expand Up @@ -980,6 +1031,16 @@ impl<R: Runtime> PluginStore<R> {
.for_each(|plugin| plugin.on_event(app, event))
}

/// Runs the cleanup_before_exit hook for all plugins in the store.
pub(crate) fn cleanup_before_exit(&mut self, app: &AppHandle<R>) {
self.store.iter_mut().for_each(|plugin| {
#[cfg(feature = "tracing")]
let _span =
tracing::trace_span!("plugin::hooks::cleanup_before_exit", name = plugin.name()).entered();
plugin.cleanup_before_exit(app)
})
}

/// Runs the plugin [`Plugin::extend_api`] hook if it exists. Returns whether the invoke message was handled or not.
///
/// The message is not handled when the plugin exists **and** the command does not.
Expand Down Expand Up @@ -1060,3 +1121,31 @@ impl<'de> Deserialize<'de> for PermissionState {
}
}
}

#[cfg(test)]
mod tests {
use super::{Builder, TauriPlugin};
use crate::test::{MockRuntime, mock_builder, mock_context, noop_assets};
use std::sync::{
Arc,
atomic::{AtomicBool, Ordering},
};

#[test]
fn builder_cleanup_before_exit_hook_runs_on_app_cleanup() {
let called = Arc::new(AtomicBool::new(false));
let called_ = called.clone();
let plugin: TauriPlugin<MockRuntime> = Builder::new("cleanup-test")
.on_cleanup_before_exit(move |_app| called_.store(true, Ordering::SeqCst))
.build();

let app = mock_builder()
.plugin(plugin)
.build(mock_context(noop_assets()))
.unwrap();

app.cleanup_before_exit();

assert!(called.load(Ordering::SeqCst));
}
}
Loading