feat: 强力关闭场景

This commit is contained in:
zpff 2025-08-13 16:09:52 +08:00
parent ab024afb30
commit 614b13e58c
2 changed files with 25 additions and 19 deletions

View File

@ -143,7 +143,6 @@ class GazeboSimHttpServer(HttpRPCServer):
# 关闭现有场景 # 关闭现有场景
if self.scene_mgr.running_scene: if self.scene_mgr.running_scene:
self.shut_scene() self.shut_scene()
time.sleep(25)
# 启动场景 # 启动场景
self.scene_mgr.start_scene(id) self.scene_mgr.start_scene(id)
self.model_mgr = ModelManager() self.model_mgr = ModelManager()
@ -163,11 +162,8 @@ class GazeboSimHttpServer(HttpRPCServer):
try: try:
if not self.scene_mgr.running_scene: if not self.scene_mgr.running_scene:
raise RuntimeError('No scene is running') raise RuntimeError('No scene is running')
self.scene_mgr.shut_scene()
def shutt(): time.sleep(5)
self.scene_mgr.shut_scene_truly()
threading.Thread(target=shutt, daemon=True).start()
self.model_mgr = None self.model_mgr = None
except Exception as e: except Exception as e:
ret['code'] = 400 ret['code'] = 400

View File

@ -89,21 +89,9 @@ class SceneManager:
self.pid_file = None self.pid_file = None
self.sim_process.terminate() self.sim_process.terminate()
print(f'killed launch PID: {self.sim_process.pid}') print(f'killed launch PID: {self.sim_process.pid}')
# 杀死gazebo和rviz self.kill_all_processes()
subprocess.Popen(['pkill', '-15', '-f', 'gzserver'])
subprocess.Popen(['pkill', '-15', '-f', 'gzclient'])
subprocess.Popen(['pkill', '-15', '-f', 'rviz'])
self.sim_process = None
self.running_scene = None self.running_scene = None
def shut_scene_truly(self):
id = self.running_scene
self.shut_scene()
time.sleep(2)
self.start_scene(id)
time.sleep(15)
self.shut_scene()
def run_script(self, name): def run_script(self, name):
if not self.running_scene: if not self.running_scene:
raise RuntimeError('no scene running') raise RuntimeError('no scene running')
@ -113,6 +101,28 @@ class SceneManager:
raise ValueError(f'script {name} not found') raise ValueError(f'script {name} not found')
subprocess.Popen(['bash', script_path]) subprocess.Popen(['bash', script_path])
def kill_all_processes(self):
try:
# 获取所有进程
output = subprocess.check_output(["ps", "aux"]).decode()
# 过滤出目标进程
target_pids = []
for line in output.splitlines():
# 排除包含"gazebo_world_manager"的进程
if any(x in line for x in ["ros", "rviz", "gazebo"]) and "grep" not in line and "gazebo_world_manager" not in line:
target_pids.append(line.split()[1]) # 提取PID
if target_pids:
# 批量kill
subprocess.run(["kill", "-9"] + target_pids)
print(f"Killed PIDs: {', '.join(target_pids)}")
else:
print("No matching processes running.")
except subprocess.CalledProcessError as e:
print(f"Error: {e}")
if __name__ == '__main__': if __name__ == '__main__':
mgr = SceneManager() mgr = SceneManager()