If you have a Python/Perl/Ruby script you want to kill, killall
won't help you since killall
will just look for "python" or "perl", it can't match the name of a specific script.
To kill all processes older than X seconds where any part of the full running command matches a string, you can run this as root:
MAX_SECONDS=43200
PROGRAM_THAT_NEEDS_TO_DIE=bad-python-script.py
ps -eo pid,etimes \
| grep -v PID \
| awk '$2>'$MAX_SECONDS'{ print $1 }' \
| xargs --no-run-if-empty ps -f --pid \
| grep $PROGRAM_THAT_NEEDS_TO_DIE \
| awk '{ print $2 }' \
| xargs --no-run-if-empty kill -9
Use ps
to get a list of all processes (-e
) and only output the pid and the elapsed number of seconds (-o pid,etimes
).
grep -v PID
to remove the header line.
Use awk
to only select lines where the elapsed seconds are greater than 43200s (12 hours), and to strip out just the first column with the PIDs.
Pass the list of PIDs back to ps
to get the full process listing.
Use grep
to find the lines that contain the name of the script that you want to kill.
Use awk
again to pull out the PID of the script.
If there are any processes found, kill them.