trunks: Stop background thread when exiting trunksd

The background thread may access and holds references to
BackgroundCommandTransceiver, ResourceManager and other objects,
created by the main thread. Stop the background thread
before these objects are destroyed when the daemon exits.

TEST=reboot without trunksd coredump in /var/spool/crash

Change-Id: I0ed0a2a6853114066a683ae6be977dcc977b4c34
Commit-Ready: Andrey Pronin <>
Tested-by: Andrey Pronin <>
Reviewed-by: Ben Chan <>
diff --git a/trunks/ b/trunks/
index f5134c6..eaaf046 100644
--- a/trunks/
+++ b/trunks/
@@ -143,5 +143,10 @@
   LOG(INFO) << "Trunks service started.";
-  return service.Run();
+  int exit_code = service.Run();
+  // Need to stop the background thread before destroying ResourceManager
+  // and PowerManager. Otherwise, a task posted by BackgroundCommandTransceiver
+  // may attempt to access those destroyed objects.
+  background_thread.Stop();
+  return exit_code;