Skip to content

Instantly share code, notes, and snippets.

@stnvh
Last active February 25, 2016 12:17
Show Gist options
  • Save stnvh/503f417c7556f123555a to your computer and use it in GitHub Desktop.
Save stnvh/503f417c7556f123555a to your computer and use it in GitHub Desktop.
A script to kill a process if it's execution time has elapsed a specified amount of seconds
#!/bin/bash
# checks if a process has ran for n seconds, and kills it if so
# - usage killafter <procname> <seconds>
func="$1"
timeout="$2"
green="\033[31m"
red="\033[31m"
dim="\033[2m"
bold="\033[1m"
rset="\033[0m"
if [[ ! "$func" ]] || [[ ! "$timeout" ]]; then
echo "usage: killafter <procname> <seconds>"
echo -e "$dim - kills a process if its executon time has elapsed after n seconds $rset"
exit;
fi
pids=($(pgrep $func))
if [[ ! $pids ]]; then
echo -e $red"error$rset - no processes found by name '$func'"
exit
fi
for pid in "${pids[@]}"; do
elaps=($(echo "$(ps -p $pid -o etime=)" | sed -E 's/0([0-9])/\1/g' | sed -E 's/:/ /g'))
if [[ ${#elaps[@]} -eq 3 ]]; then
secs=$((${elaps[0]} * 60 * 60 + ${elaps[1]} * 60 + ${elaps[2]}))
else
secs=$((${elaps[0]} * 60 + ${elaps[1]}))
fi
echo -e "$dim------$rset"
echo -en "$bold$pid$rset ($dim$func$rset): elapsed for $secs seconds -"
if [[ "$secs" -ge "$timeout" ]]; then
kill $pid
echo -e "$red killed"
else
echo -e "$green kept.. for now"
fi
echo -en "$rset"
done
echo -e "$dim------$rset"
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Label</key>
<string>local.stan.phpkill</string>
<key>ProgramArguments</key>
<array>
<string>/bin/sh</string>
<string>-c</string>
<string>~/bin/killafter</string>
<string>php</string>
<string>15</string>
</array>
<key>StartInterval</key>
<integer>15</integer>
</dict>
</plist>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment