Nav2 Navigation Stack - jazzy  jazzy
ROS 2 Navigation Stack
utils.py
1 #! /usr/bin/env python3
2 # Copyright 2024 Open Navigation LLC
3 # Copyright 2024 Stevedan Ogochukwu Omodolor Omodia
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16 
17 """General utility functions."""
18 
19 import os
20 import signal
21 import subprocess
22 
23 
24 def find_os_processes(name):
25  """Find all the processes that are running gz sim."""
26  ps_output = subprocess.check_output(['ps', 'aux'], text=True)
27  ps_lines = ps_output.split('\n')
28  gz_sim_processes = []
29  for line in ps_lines:
30  if name in line:
31  columns = line.split()
32  pid = columns[1]
33  command = ' '.join(columns[10:])
34  if command.startswith(name):
35  gz_sim_processes.append((pid, command))
36  return gz_sim_processes
37 
38 
39 def kill_process(pid):
40  """Kill a process with a given PID."""
41  try:
42  os.kill(int(pid), signal.SIGKILL)
43  print(f'Successfully killed process with PID: {pid}')
44  except Exception as e:
45  print(f'Failed to kill process with PID: {pid}. Error: {e}')
46 
47 
48 def kill_os_processes(name):
49  """Kill all processes that are running with name."""
50  processes = find_os_processes(name)
51  if processes:
52  for pid, _ in processes:
53  kill_process(pid)
54  else:
55  print(f'No processes found starting with {name}')