How to properly terminate ROS and Gazebo

ROS and Gazebo have many components running in the background. To properly terminate the program, one can use the ps command to collect all the related process IDs and then kill them manually. Here is a python utility code that collects the process IDs in the ps command outputs and execute the kill -9 command.

import sys
import subprocess

if __name__ == '__main__':
    result = []

    for _line in sys.stdin:
        line = _line.strip()
        if line:
            k = line.find(' ')
            while k < len(line) and line[k] == ' ':
                k += 1

            end_index = line.find(' ', k)
            result.append(line[k:end_index])

    command = ["kill", "-9"]
    command.extend(result[:-1])
    subprocess.run(command)

We can create an alias for this utility script, say, alias kill-all="python <path-to-script>". To usage the script, we can do

ps aux | grep -i ros | kill-all
ps aux | grep -i gazebo | kill-all

Last updated