Created
June 1, 2017 14:47
-
-
Save Pamblam/5a78ac94dc98d91359b253189b282e68 to your computer and use it in GitHub Desktop.
Monitor and kill a process when it has been idle for 10 minutes (in this case, Oracle) - Written on mac, not tested on linux
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# The name of the process to search for and kill | |
PROCESSNAME="oracle"; | |
# Determine if this script is currently running | |
if [ -f omstatus ]; then | |
# The status file exists, wait a second and see if it changes | |
CURRENTSTATUS=$(cat omstatus); sleep 2; | |
NEWSTATUS=$(cat omstatus); | |
if [ "$CURRENTSTATUS" == "$NEWSTATUS" ]; then | |
RUNNING="0"; | |
else | |
RUNNING="1"; | |
echo "$CURRENTSTATUS"; | |
fi | |
else | |
RUNNING="0"; | |
fi | |
# Only run the script if it's not already running | |
if [ "$RUNNING" == "0" ]; then | |
echo "Starting process monitor"; | |
while true; | |
do | |
# Get programs's process ID | |
PID=$(ps -A | grep -m1 "$PROCESSNAME" | awk '{print $1}'); | |
# Get process state | |
STATE=$(top -l 1 -pid $PID -stats "state" | tail -1); | |
# Get the time now | |
NOW=$(date +%s); | |
if [ "" != "$STATE" ]; then | |
# If program is not sleeping, take note of the time | |
if [ "$STATE" != "sleeping" ]; then | |
echo "$NOW" >| time; | |
fi | |
# Get the last time the process was not sleeping, which is saved in a file called "time" | |
if [ -f time ]; then | |
TIME=$(cat time); | |
else | |
TIME=$(date +%s); | |
fi | |
# How long since last time process was not sleeping | |
SINCE=$(expr "$NOW" - "$TIME"); | |
# If it's been sleeping for 10 minutes, kill it | |
if [ $SINCE -gt 600 ]; then | |
if [ -f time ]; then | |
rm time; | |
fi | |
kill -9 $PID > /dev/null 2>&1; | |
fi | |
# Update status | |
echo "$PROCESSNAME (PID: $PID) was $STATE for $SINCE seconds at $NOW" >| omstatus; | |
else | |
# Update status | |
echo "$PROCESSNAME (PID: $PID) was not running at $NOW" >| omstatus; | |
fi | |
done & | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment