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.
Explanation
for Loop
This iterates through process IDs. Replace target_name
with the condition string you want to filter on to find the desired processes.
Set line
Outputs the PID and etimes and retrieves the line for the specified PID.
Set duration
Extracts the execution time from the ps
result. The time is in seconds.
-z $duration
If there is no process, it moves on to the next iteration.
$duration -ge 345600
If the process has been running for more than 345,600 seconds (4 days), it terminates it. It does so using sudo kill $pid
.