Make all host processes run with the instance dir as working dir

This ensures stop_cvd will find them all and kill them when it can't
get the launcher to stop itself.

Bug: 140581232
Test: locally
Change-Id: Iea8a178704b8c8ccf23bd5867bb64a88d3767798
diff --git a/host/commands/launch/main.cc b/host/commands/launch/main.cc
index bb2d5ae..88853fa 100644
--- a/host/commands/launch/main.cc
+++ b/host/commands/launch/main.cc
@@ -315,6 +315,18 @@
 
   auto config = InitFilesystemAndCreateConfig(&argc, &argv);
 
+  // Change working directory to the instance directory as early as possible to
+  // ensure all host processes have the same working dir. This helps stop_cvd
+  // find the running processes when it can't establish a communication with the
+  // launcher.
+  auto chdir_ret = chdir(config->instance_dir().c_str());
+  if (chdir_ret != 0) {
+    auto error = errno;
+    LOG(ERROR) << "Unable to change dir into instance directory ("
+               << config->instance_dir() << "): " << strerror(error);
+    return LauncherExitCodes::kInstanceDirCreationError;
+  }
+
   auto vm_manager = vm_manager::VmManager::Get(config->vm_manager(), config);
 
   // Check host configuration
diff --git a/host/commands/stop_cvd/main.cc b/host/commands/stop_cvd/main.cc
index b631d75..e22e74c 100644
--- a/host/commands/stop_cvd/main.cc
+++ b/host/commands/stop_cvd/main.cc
@@ -54,7 +54,10 @@
 std::set<pid_t> GetCandidateProcessGroups() {
   std::string cmd = "fuser";
   // Add the instance directory
-  cmd += " " + cvd::StringFromEnv("HOME", ".") + "/cuttlefish_runtime/*";
+  auto instance_dir = cvd::StringFromEnv("HOME", ".") + "/cuttlefish_runtime";
+  cmd += " " + instance_dir;
+  // Add files in instance dir
+  cmd += " " + instance_dir + "/*";
   // Add the shared memory file
   cmd += " " + vsoc::GetPerInstanceDefault("/dev/shm/cvd-");
   std::shared_ptr<FILE> cmd_out(popen(cmd.c_str(), "r"), pclose);