Table of Contents
I’m sure everyone has had the experience of a server process that was created by some developer and continues to run indefinitely without ending. This script comes in handy in such situations. When you schedule it to run regularly with tools like crontab, it will terminate these seemingly never-ending processes for you. It’s similar to scripts like Terminating Excessive Apache (httpd) Child Processes and Listing Process Execution Directories.
Code
I ran this on an AWS EC2 Amazon Linux server.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
#!/bin/bash for pid in `ps aux | grep crawler | grep -v grep | tr -s ' ' | cut -d ' ' -f2` do line=`ps --pid ${pid} -eo pid,etimes | grep ${pid}` duration=`cut -d' ' -f 2 <<< ${line}` if [ -z $duration ] then continue fi if [ $duration -ge 345600 ] then echo $duration sudo kill $pid fi done |
Explanation
for Loop
1 |
for pid in `ps aux | grep target_name | grep -v grep | tr -s ' ' | cut -d ' ' -f2` |
This iterates through process IDs. Replace target_name
with the condition string you want to filter on to find the desired processes.
Set line
1 |
line=`ps --pid ${pid} -eo pid,etimes | grep ${pid}` |
Outputs the PID and etimes and retrieves the line for the specified PID.
Set duration
1 |
duration=`cut -d' ' -f 2 <<< ${line}` |
Extracts the execution time from the ps
result. The time is in seconds.
-z $duration
1 2 3 4 |
if [ -z $duration ] then continue fi |
If there is no process, it moves on to the next iteration.
$duration -ge 345600
1 2 3 4 5 |
if [ $duration -ge 345600 ] then echo $duration sudo kill $pid fi |
If the process has been running for more than 345,600 seconds (4 days), it terminates it. It does so using sudo kill $pid
.